package com.jeeplus.modules.api;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.jeeplus.modules.api.utils.BadWordUtils;
import com.jeeplus.modules.api.utils.*;
import com.jeeplus.modules.group.entity.Group;
import com.jeeplus.modules.group.service.GroupService;
import com.jeeplus.modules.groupbill.entity.GroupBill;
import com.jeeplus.modules.groupbill.service.GroupBillService;
import com.jeeplus.modules.groupcash.entity.GroupCash;
import com.jeeplus.modules.groupcash.service.GroupCashService;
import com.jeeplus.modules.hkqy.service.HkqyService;
import com.jeeplus.modules.ordertask.entity.Ordertask;
import com.jeeplus.modules.ordertask.mapper.OrdertaskMapper;
import com.jeeplus.modules.ordertask.service.OrdertaskService;
import com.jeeplus.modules.ptc.service.PtcService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.IdGen;
import com.jeeplus.common.utils.net.HttpClientUtil;
import com.jeeplus.common.utils.time.DateFormatUtil;
import com.jeeplus.common.utils.time.DateUtil;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.access.entity.Access;
import com.jeeplus.modules.access.service.AccessService;
import com.jeeplus.modules.address.entity.Address;
import com.jeeplus.modules.address.service.AddressService;
import com.jeeplus.modules.api.req.ReqJson;
import com.jeeplus.modules.api.res.ResJson;
import com.jeeplus.modules.api.service.ApiService;
import com.jeeplus.modules.banner.entity.Banner;
import com.jeeplus.modules.banner.service.BannerService;
import com.jeeplus.modules.cart.entity.Cart;
import com.jeeplus.modules.cart.service.CartService;
import com.jeeplus.modules.cashprop.entity.CashProp;
import com.jeeplus.modules.cashprop.service.CashPropService;
import com.jeeplus.modules.collectstore.entity.CollectStore;
import com.jeeplus.modules.collectstore.service.CollectStoreService;
import com.jeeplus.modules.comment.entity.Comment;
import com.jeeplus.modules.comment.service.CommentService;
import com.jeeplus.modules.couponorder.entity.CouponOrder;
import com.jeeplus.modules.couponorder.service.CouponOrderService;
import com.jeeplus.modules.faq.entity.Faq;
import com.jeeplus.modules.faq.service.FaqService;
import com.jeeplus.modules.grouporder.entity.GroupOrder;
import com.jeeplus.modules.grouporder.service.GroupOrderService;
import com.jeeplus.modules.grouprefund.entity.GroupRefund;
import com.jeeplus.modules.grouprefund.service.GroupRefundService;
import com.jeeplus.modules.jdcategory.entity.JdCategory;
import com.jeeplus.modules.jdcategory.service.JdCategoryService;
import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.member.service.MemberService;
import com.jeeplus.modules.message.entity.Message;
import com.jeeplus.modules.message.service.MessageService;
import com.jeeplus.modules.msg.service.MsgService;
import com.jeeplus.modules.orderrefund.entity.OrderRefund;
import com.jeeplus.modules.orderrefund.service.OrderRefundService;
import com.jeeplus.modules.feedback.entity.Feedback;
import com.jeeplus.modules.feedback.service.FeedbackService;
import com.jeeplus.modules.paytype.entity.PayType;
import com.jeeplus.modules.paytype.service.PayTypeService;
import com.jeeplus.modules.pddcategory.entity.PddCategory;
import com.jeeplus.modules.pddcategory.service.PddCategoryService;
import com.jeeplus.modules.pickday.service.PickDayService;
import com.jeeplus.modules.product.entity.Product;
import com.jeeplus.modules.product.entity.ProductSkuname;
import com.jeeplus.modules.product.mapper.ProductSkunameMapper;
import com.jeeplus.modules.product.service.ProductService;
import com.jeeplus.modules.productcategory.entity.ProductCategory;
import com.jeeplus.modules.productcategory.service.ProductCategoryService;
import com.jeeplus.modules.productgift.entity.ProductGift;
import com.jeeplus.modules.productgift.service.ProductGiftService;
import com.jeeplus.modules.productgroup.service.ProductGroupService;
import com.jeeplus.modules.productorder.entity.OrderItem;
import com.jeeplus.modules.productorder.entity.ProductOrder;
import com.jeeplus.modules.productorder.mapper.OrderItemMapper;
import com.jeeplus.modules.productorder.service.ProductOrderService;
import com.jeeplus.modules.productsku.entity.ProductSku;
import com.jeeplus.modules.productsku.service.ProductSkuService;
import com.jeeplus.modules.proxylog.service.ProxyLogService;
import com.jeeplus.modules.proxyorder.entity.ProxyOrder;
import com.jeeplus.modules.proxyorder.service.ProxyOrderService;
import com.jeeplus.modules.proxyprice.entity.ProxyPrice;
import com.jeeplus.modules.proxyprice.service.ProxyPriceService;
import com.jeeplus.modules.proxyproduct.entity.ProxyProduct;
import com.jeeplus.modules.proxyproduct.service.ProxyProductService;
import com.jeeplus.modules.reason.entity.Reason;
import com.jeeplus.modules.reason.service.ReasonService;
import com.jeeplus.modules.shop.entity.Shop;
import com.jeeplus.modules.shop.service.ShopService;
import com.jeeplus.modules.shopbill.entity.ShopBill;
import com.jeeplus.modules.shopbill.service.ShopBillService;
import com.jeeplus.modules.shopcash.entity.ShopCash;
import com.jeeplus.modules.shopcash.service.ShopCashService;
import com.jeeplus.modules.shopcategory.entity.ShopCategory;
import com.jeeplus.modules.shopcategory.service.ShopCategoryService;
import com.jeeplus.modules.shopcoupon.entity.ShopCoupon;
import com.jeeplus.modules.shopcoupon.service.ShopCouponService;
import com.jeeplus.modules.specialproduct.entity.SpecialProduct;
import com.jeeplus.modules.specialproduct.service.SpecialProductService;
import com.jeeplus.modules.store.entity.Store;
import com.jeeplus.modules.store.service.StoreService;
import com.jeeplus.modules.storescore.entity.StoreScore;
import com.jeeplus.modules.storescore.service.StoreScoreService;
import com.jeeplus.modules.sys.entity.Area;
import com.jeeplus.modules.sys.service.AreaService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.tags.entity.Tags;
import com.jeeplus.modules.tags.service.TagsService;
import com.jeeplus.modules.tamoybrand.service.TAmoyBrandService;
import com.jeeplus.modules.taokeorder.entity.TTaokeOrder;
import com.jeeplus.modules.taokeorder.service.TTaokeOrderService;
import com.jeeplus.modules.tsupport.entity.TSupport;
import com.jeeplus.modules.tsupport.service.TSupportService;
import com.jeeplus.modules.upgrade.entity.Upgrade;
import com.jeeplus.modules.upgrade.service.UpgradeService;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.internal.util.WebUtils;
import com.taobao.api.request.TbkScPublisherInfoSaveRequest;
import com.taobao.api.response.TbkScPublisherInfoSaveResponse;

import net.oschina.j2cache.CacheProviderHolder;

import javax.ws.rs.Encoded;

/**
 * APP接口
 * @author Administrator
 *
 */
@CrossOrigin(origins = "*")
@Controller
@RequestMapping(value = "/api")
public class ApiController2 extends BaseController {
	@Autowired
	private MemberService memberService;
	@Autowired
	private OrdertaskService ordertaskService;
	@Autowired
	private OrdertaskMapper ordertaskMapper;
	@Autowired
	private StoreService storeService;
	@Autowired
	private ShopService shopService;
	@Autowired
	private GroupService groupService;
	@Autowired
	private GroupBillService groupBillService;
	@Autowired
	private GroupCashService groupCashService;
	@Autowired
	private ShopCategoryService shopCategoryService;
	@Autowired
	private ProductService productService;
	@Autowired
	private CollectStoreService collectStoreService;
	@Autowired
	private StoreScoreService storeScoreService;
	@Autowired
	private ProxyOrderService proxyOrderService;
	@Autowired
	private FaqService faqService;
	@Autowired
	private AddressService addressService;
	@Autowired
	private CartService cartService;
	@Autowired
	private ProductSkuService productSkuService;
	@Autowired
	private ProductOrderService productOrderService;
	@Autowired
	private PtcService ptcService;
	@Autowired
	private HkqyService hkqyService;
	@Autowired
	private PayTypeService payTypeService;
	@Autowired
	private ShopCashService shopCashService;
	@Autowired
	private ShopBillService shopBillService;
	@Autowired
	private ShopCouponService shopCouponService;
	@Autowired
	private CouponOrderService couponOrderService;
	@Autowired
	private ReasonService reasonService;
	@Autowired
	private OrderRefundService orderRefundService;
	@Autowired
	private FeedbackService feedbackService;
	@Autowired
	private OrderItemMapper orderItemMapper;
	@Autowired
	private CommentService commentService;
	@Autowired
	private UpgradeService upgradeService;
	@Autowired
	private BannerService bannerService;
	@Autowired
	private ProductCategoryService productCategoryService;
	@Autowired
	private TagsService tagsService;
	@Autowired
	private SpecialProductService specialProductService;
	@Autowired
	private ProxyPriceService proxyPriceService;
	@Autowired
	private AreaService areaService;
	@Autowired
	private MessageService messageService;
	@Autowired
	private TSupportService tSupportService;
	@Autowired
	private ProductSkunameMapper productSkunameMapper;
	@Autowired
	private ProductGiftService productGiftService;
	@Autowired
	private ProductGroupService productGroupService;
	@Autowired
	private AccessService accessService;
	@Autowired
	private GroupOrderService groupOrderService;
	@Autowired
	private ApiService apiService;
	@Autowired
	private ProxyProductService proxyProductService;
	@Autowired
	private MsgService msgService;
	@Autowired
	private TTaokeOrderService tTaokeOrderService;
	@Autowired
	private PddCategoryService pddCategoryService;
	@Autowired
	private GroupRefundService groupRefundService;
	@Autowired
	private JdCategoryService jdCategoryService;
	@Autowired
	private CashPropService cashPropService;

	@PostMapping("/insertPddCategory")
	@ResponseBody
	public ResJson insertPddCategory(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			// 一级分类列表
			Map<String, String> params = Maps.newHashMap();
			params.put("parent_opt_id", "0");
			JSONObject jsonObject = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.getpddopts, params);
			logger.debug("喵有券返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("code"))) {
				res.setResultNote(jsonObject.getString("msg"));
				return res;
			}
			JSONArray dataArray = jsonObject.getJSONArray("data");
			if (dataArray != null) {
				for (int i = 0; i < dataArray.size(); i++) {
					JSONObject c = dataArray.getJSONObject(i);
					PddCategory pddCategory = new PddCategory();
					pddCategory.setIsNewRecord(true);
					pddCategory.setId(c.getString("opt_id"));
					pddCategory.setName(c.getString("opt_name"));
					pddCategory.setSort(i + 1);
					pddCategory.setState(i < 10 ? "0" : "1");
					pddCategoryService.save(pddCategory);

				}
			}
			res.setResult("0");
			res.setResultNote("导入成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	@PostMapping("/insertJdCategory")
	@ResponseBody
	public ResJson insertJdCategory(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			// 一级分类列表
			Map<String, String> params = Maps.newHashMap();
			params.put("parent_id", "0");
			params.put("grade", "0");
			JSONObject jsonObject = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.getItemCateInfo, params);
			logger.debug("喵有券返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("code"))) {
				res.setResultNote(jsonObject.getString("msg"));
				return res;
			}
			JSONArray dataArray = jsonObject.getJSONArray("data");
			if (dataArray != null) {
				for (int i = 0; i < dataArray.size(); i++) {
					JSONObject c = dataArray.getJSONObject(i);
					JdCategory jdCategory = new JdCategory();
					jdCategory.setIsNewRecord(true);
					jdCategory.setId(c.getString("id"));
					jdCategory.setName(c.getString("name"));
					jdCategory.setSort(i + 1);
					jdCategory.setState(i < 10 ? "0" : "1");
					jdCategoryService.save(jdCategory);

				}
			}
			res.setResult("0");
			res.setResultNote("导入成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 推荐店铺列表
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/recommendShopList")
	@ResponseBody
	public ResJson recommendShopList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		List<Map<String, Object>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("type"))) {
				res.setResultNote("TYPE类型不能为空！");
				return res;
			}
			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}
			if ("0".equals(req.getString("type"))) {// 厂家列表
				Store store = new Store();
				store.setInvite(new Member(req.getString("uid")));
				store.setState("0");
				store.setAuditState("2");
				Page<Store> page = storeService.findPage(new Page<Store>(req.getPageNo(), req.getPageSize()), store);
				for (Store n : page.getList()) {
					Map<String, Object> map = Maps.newHashMap();
					map.put("shopId", n.getId());
					map.put("shopName", n.getTitle());
					dataList.add(map);
				}
				res.setTotalPage(page.getTotalPage());
			} else {// 实体商家列表
				Shop shop = new Shop();
				shop.setInvite(new Member(req.getString("uid")));
				shop.setState("0");
				shop.setAuditState("2");
				Page<Shop> page = shopService.findPage(new Page<Shop>(req.getPageNo(), req.getPageSize()), shop);
				for (Shop n : page.getList()) {
					Map<String, Object> map = Maps.newHashMap();
					map.put("shopId", n.getId());
					map.put("shopName", n.getTitle());
					dataList.add(map);
				}
				res.setTotalPage(page.getTotalPage());
			}
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 商品管理列表
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/productList")
	@ResponseBody
	public ResJson productList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		List<Map<String, Object>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getString("factoryId"))) {
				res.setResultNote("厂家ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("type"))) {
				res.setResultNote("TYPE类型不能为空！");
				return res;
			}
			Store store = storeService.get(req.getString("factoryId"));
			if (store == null) {
				res.setResultNote("该厂家不存在！");
				return res;
			}
			Product product = new Product();
			product.setStore(store);
			product.setAuditState("1");
			product.setState(req.getString("type"));
			Page<Product> page = productService.findPage(new Page<Product>(req.getPageNo(), req.getPageSize()),
					product);
			for (Product n : page.getList()) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", n.getId());
				map.put("name", n.getTitle());
				map.put("coverImage", getRealImage(n.getIcon()));
				map.put("price", n.getPrice());
				dataList.add(map);
			}
			res.setTotalPage(page.getTotalPage());
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 店铺订单管理
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/factoryOrderList")
	@ResponseBody
	public ResJson factoryOrderList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		List<Map<String, Object>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getString("factoryId"))) {
				res.setResultNote("店铺ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("type"))) {
				res.setResultNote("TYPE类型不能为空！");
				return res;
			}
			Store store = storeService.get(req.getString("factoryId"));
			if (store == null) {
				res.setResultNote("该商家不存在！");
				return res;
			}

			// 获取订单各类型数量
			// 订单状态0-待付，1-待发，2-待收，3-待评，4-已评，5-取消，6-退款中，7-已退款
			String count1 = "0";// 待发货数量
			String count2 = "0";// 待收货数量
			String count3 = "0";// 售后数量
			String count4 = "0";// 已完成数量
			List<Map<String,Object>> list = productOrderService.executeSelectSql("SELECT a.state state,COUNT(*) count FROM t_product_order a WHERE a.store_id = '"+store.getId()+"' GROUP BY a.state ");
			if (list != null && !list.isEmpty()) {
				for (Map<String, Object> map : list) {
					String state = map.get("state").toString();
					if ("1".equals(state)) {
						count1 = map.get("count").toString();
					} else if ("2".equals(state)) {
						count2 = map.get("count").toString();
					} else if ("6".equals(state)) {
						count3 = map.get("count").toString();
					} else if ("3".equals(state)) {
						count4 = map.get("count").toString();
					}
				}
			}
			res.put("count1", count1);
			res.put("count2", count2);
			res.put("count3", count3);
			res.put("count4", count4);

			ProductOrder productOrder = new ProductOrder();
			productOrder.setStore(store);
			if ("1".equals(req.getString("type"))) {// 待发货
				productOrder.setState("1");
			} else if ("2".equals(req.getString("type"))) {// 已发货
				productOrder.setState("2");
			} else if ("3".equals(req.getString("type"))) {// 售后
				productOrder.setState("6");
			} else if ("4".equals(req.getString("type"))) {
				productOrder.setState("3");
			}

			Page<ProductOrder> page = productOrderService.findPage(new Page<ProductOrder>(req.getPageNo(), req.getPageSize()), productOrder);
			for (ProductOrder n : page.getList()) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("orderId", n.getId());
				map.put("shopName", n.getStore().getTitle());
				map.put("orderNum", n.getId());
				map.put("status", n.getState());
				map.put("isProxy", n.getProxyType());
				map.put("payMoney", n.getAmount());
				map.put("payMoney", n.getAmount());
				List<Map<String, Object>> productList = new ArrayList<Map<String, Object>>();
				OrderItem orderItem = new OrderItem();
				orderItem.setOrder(n);
				// 订单商品列表
				List<OrderItem> opList = orderItemMapper.findList(orderItem);
				if (opList != null && opList.size() > 0) {
					for (OrderItem op : opList) {
						Map<String, Object> map1 = new HashMap<String, Object>();
						map1.put("productId", op.getProductId());
						map1.put("productName", op.getProductTitle());
						map1.put("productCode", op.getProductCode());
						map1.put("coverImage", getRealImage(op.getProductIcon()));
						map1.put("specification", op.getSkuName());
						map1.put("integral", op.getPoint());
						map1.put("price", op.getPrice());
						map1.put("count", op.getQty());
						productList.add(map1);
					}
				}
				map.put("productList", productList);
				dataList.add(map);
			}
			res.setTotalPage(page.getTotalPage());
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}


	/**
	 * 实体商家入驻所属行业分类列表
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/industryList")
	@ResponseBody
	public ResJson industryList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		List<Map<String, Object>> dataList = Lists.newArrayList();
		try {
			ShopCategory shopCategory = new ShopCategory();
			shopCategory.setState("0");
			List<ShopCategory> scList = shopCategoryService.findList(shopCategory);
			if (scList != null && scList.size() > 0) {
				for (ShopCategory n : scList) {
					Map<String, Object> map = Maps.newHashMap();
					map.put("id", n.getId());
					map.put("name", n.getTitle());
					dataList.add(map);
				}
			}
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 实体商家入驻
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/shopEnter")
	@ResponseBody
	public ResJson shopEnter(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("申请失败！");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("logo"))) {
				res.setResultNote("请选择上传店铺LOGO！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("shopName"))) {
				res.setResultNote("请输入商家名称！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("categoryId"))) {
				res.setResultNote("请选择所属行业！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("address"))) {
				res.setResultNote("请选择商户地址！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("lngAndLat"))) {
				res.setResultNote("经纬度不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("contactName"))) {
				res.setResultNote("请输入联系人名称！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("contactTele"))) {
				res.setResultNote("请输入联系人电话！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("contractorTele"))) {
				res.setResultNote("请输入签约人电话！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("businessLicense"))) {
				res.setResultNote("请上传营业执照！");
				return res;
			}
			JSONArray jsonArray = req.getJSONArray("idCardImage");
			if (jsonArray == null || jsonArray.isEmpty()) {
				res.setResultNote("请上传身份证照！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("city"))) {
				res.setResultNote("城市不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("hyrebate"))) {
				res.setResultNote("会员返利比例不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("ptrebate"))) {
				res.setResultNote("平台返利比例（铜板）不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("payMoney"))) {
				res.setResultNote("选择的支付金额不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("state"))) {
				res.setResultNote("选择的支付类型不能为空！");
				return res;
			}
			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}
			List<WohuiEntity> entityList = Lists.newArrayList();
			entityList.add(new WohuiEntity("phone", req.getString("contractorTele")));
			JSONObject object = WohuiUtils.send(WohuiUtils.GetUInfoByPhone, entityList);
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote(object.getString("respMsg"));
				return res;
			}
			JSONArray array = object.getJSONArray("data");
			JSONObject obj = array.getJSONObject(0);
			String guid = obj.getString("C_GUID");
			String IsCFM="0";
			if (StringUtils.isNotBlank(obj.getString("C_Roles"))) {
				String[] roles = obj.getString("C_Roles").split(",");
				List<String> rolesList = Arrays.asList(roles);
				if (rolesList.contains("C2F创客") || rolesList.contains("云店铺") ) {
					IsCFM = "1";
				}
			}
			if(!"1".equals(IsCFM)){
				res.setResultNote("该签约人不是C2F创客,请重新选择签约人！");
				return res;
			}

			// 判断状态
			Shop shop = shopService.findUniqueByProperty("uid", member.getId());
			if (shop != null) {
				if ("1".equals(shop.getAuditState())) {
					res.setResultNote("申请审核中");
					return res;
				}
				if ("2".equals(shop.getAuditState())) {
					res.setResultNote("您已成为实体商家，请勿重复申请");
					return res;
				}
				if ("3".equals(shop.getAuditState())) {
					shop.setAuditState("1");
				}
				if ("4".equals(shop.getAuditState())) {
					shop.setAuditState("0");
				}
			} else {
				shop = new Shop();
				shop.setIsNewRecord(true);
				shop.setId(OrderNumPrefix.shopOrder + IdGen.getOrderNo());
				shop.setMember(member);
				shop.setState("0");
				shop.setAuditState("0");
				shop.setBalance("0");
				shop.setShopCode("SQ" + RandomStringUtils.randomNumeric(7));
				shop.setCouponCode("MD" + RandomStringUtils.randomNumeric(5));
			}

			shop.setTitle(req.getString("shopName"));
			shop.setIcon(req.getString("logo"));
			shop.setCategory(new ShopCategory(req.getString("categoryId")));
			shop.setAddress(req.getString("address"));
			shop.setLon(Double.parseDouble(req.getString("lngAndLat").split(",")[0]));
			shop.setLat(Double.parseDouble(req.getString("lngAndLat").split(",")[1]));
			shop.setUsername(req.getString("contactName"));
			shop.setPhone(req.getString("contactTele"));
			shop.setInvite(new Member(guid));
			shop.setInvitePhone(req.getString("contractorTele"));
			shop.setInviteName(obj.getString("C_RealName"));
			shop.setLicence(req.getString("businessLicense"));
			shop.setIdcard(StringUtils.join(jsonArray, "|"));
			shop.setCity(req.getString("city"));
			String	hyrebate = String.valueOf(new BigDecimal(req.getString("hyrebate")).divide(new BigDecimal("100"), 4, BigDecimal.ROUND_HALF_DOWN));
			String	ptrebate = String.valueOf(new BigDecimal(req.getString("ptrebate")).divide(new BigDecimal("100"), 4, BigDecimal.ROUND_HALF_DOWN));
			shop.setHyrebate(hyrebate);
			shop.setPtrebate(ptrebate);
			JSONArray otherImageList = req.getJSONArray("otherImage");
			if (otherImageList != null && !otherImageList.isEmpty()) {
				shop.setOthers(StringUtils.join(otherImageList, "|"));
			}
			shop.setPaymoney("0");
			shop.setAmount(req.getString("payMoney"));
			shop.setXhtype("1");

			shop.setShowState("0");
			shop.setLovetype("0");

			shopService.save(shop);
			res.put("orderNum", "0".equals(shop.getAuditState()) ? shop.getId() : "");
			res.put("amount", req.getString("payMoney"));
			res.put("state", req.getString("state"));
			res.setResult("0");
			res.setResultNote("申请成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 收藏的店列表
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/collectionShopList")
	@ResponseBody
	public ResJson collectionShopList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		List<Map<String, Object>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}
			CollectStore collectStore = new CollectStore();
			collectStore.setMember(member);
			Page<CollectStore> page = collectStoreService.findPage(new Page<CollectStore>(req.getPageNo(), req.getPageSize()), collectStore);
			for (CollectStore n : page.getList()) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("shopId", n.getStore().getId());
				map.put("shopName", n.getStore().getTitle());
				map.put("shopLogo", getRealImage(n.getStore().getIcon()));
				// 查询商家综合评分
				/*StoreScore storeScore = new StoreScore();
				storeScore.setStore(n.getStore());
				List<StoreScore> sList = storeScoreService.findList(storeScore);
				int score = 0;
				if (sList != null && sList.size() > 0) {
					for (StoreScore s : sList) {
						score += s.getScore();
					}
				}
				map.put("score", score / sList.size());*/
				String score = storeScoreService.executeGetSql("SELECT IFNULL(SUM(score)/COUNT(*),0) FROM t_store_score WHERE store_id = '"+n.getStore().getId()+"'").toString();
				map.put("score", new BigDecimal(score).setScale(1, BigDecimal.ROUND_DOWN).toString());
				dataList.add(map);
			}
			res.setTotalPage(page.getTotalPage());
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

//	/**
//	 * 我的小店商品列表
//	 *
//	 * @param req
//	 * @return
//	 */
//	@PostMapping("/smallShopList")
//	@ResponseBody
//	public ResJson smallShopList(@RequestBody ReqJson req) {
//		ResJson res = new ResJson();
//		res.setResultNote("查询失败！");
//		List<Map<String, Object>> dataList = Lists.newArrayList();
//		try {
//			if (StringUtils.isBlank(req.getString("uid"))) {
//				res.setResultNote("用户ID不能为空！");
//				return res;
//			}
//
//			// 从三方会员系统获取数据
//			List<WohuiEntity> entityList = Lists.newArrayList();
//			entityList.add(new WohuiEntity("CardGUID", req.getUid()));
//			JSONObject jsonObject = WohuiUtils.send(WohuiUtils.GetMSM, entityList);
//			if (!"0000".equals(jsonObject.getString("respCode"))) {
//				res.setResultNote(jsonObject.getString("respMsg"));
//				return res;
//			}
//
//			Set<String> set = Sets.newHashSet();
//			JSONArray jsonArray = jsonObject.getJSONArray("data");
//			for (int i = 0; i < jsonArray.size(); i++) {
//				JSONObject data = jsonArray.getJSONObject(i);
//				if ("30".equals(data.getString("MSM_Status")) || "40".equals(data.getString("MSM_Status"))) {
//					set.add(data.getString("MSM_GoodsCode"));
//				}
//			}
//
//			if (!set.isEmpty()) {
//				for (String code : set) {
//					if (StringUtils.startsWithIgnoreCase(code, ProductCode.product)) {// 云店
//						Map<String, Object> data = Maps.newHashMap();
//						data.put("proxyCode", code);
//						data.put("productType", "0");
//						data.put("productState", "0");
//						List<Map<String, Object>> productList = Lists.newArrayList();
//
//						Product product = new Product();
//						product.setCode(code);
//						product.setState("0");
//						product.setAuditState("1");
//						List<Product> list = productService.findList(product);
//						for (Product p : list) {
//							Map<String, Object> map = Maps.newHashMap();
//							map.put("productId", p.getId());
//							map.put("coverImage", getRealImage(p.getIcon()));
//							map.put("productCode", p.getCode());
//							map.put("productName", p.getTitle());
//							map.put("integral", p.getPoint());
//							map.put("type", "0");
//							map.put("state", "0");
//							productList.add(map);
//						}
//						data.put("productList", productList);
//						dataList.add(data);
//					} else if (StringUtils.startsWithIgnoreCase(code, ProductCode.alliance)) {// 淘客
//						Map<String, Object> data = Maps.newHashMap();
//						data.put("proxyCode", code);
//						data.put("productType", "1");
//						data.put("productState", "1");
//						List<Map<String, Object>> productList = Lists.newArrayList();
//
//						ProxyProduct proxyProduct = new ProxyProduct();
//						proxyProduct.setCode(code);
//						List<ProxyProduct> list = proxyProductService.findList(proxyProduct);
//						for (ProxyProduct p : list) {
//							Map<String, Object> map = Maps.newHashMap();
//							map.put("productId", p.getProductId());
//							map.put("coverImage", getRealImage(p.getProductImage()));
//							map.put("productCode", p.getCode());
//							map.put("productName", p.getProductName());
//							map.put("integral", p.getProductPoint());
//							map.put("type", p.getType());
//							map.put("state", p.getState());
//							if ("0".equals(p.getState())) {
//								data.put("productState", "0");
//							}
//							productList.add(map);
//						}
//						data.put("productList", productList);
//						dataList.add(data);
//					}
//				}
//			}
//			res.setTotalPage(1);
//			res.setDataList(dataList);
//			res.setResult("0");
//			res.setResultNote("获取成功");
//		} catch (Exception e) {
//			logger.error(e.getMessage());
//		}
//		return res;
//	}

	/**
	 * 帮助中心
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/questionList")
	@ResponseBody
	public ResJson questionList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		List<Map<String, Object>> dataList = Lists.newArrayList();
		try {
			Faq faq = new Faq();
			List<Faq> fList = faqService.findList(faq);
			for (Faq n : fList) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("title", n.getTitle());
				map.put("content", n.getContent());
				map.put("url", n.getUrl());
				dataList.add(map);
			}
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 商圈订单列表
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/sqOrderList")
	@ResponseBody
	public ResJson sqOrderList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		List<Map<String, Object>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("userType"))) {
				res.setResultNote("用户类型不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("type"))) {
				res.setResultNote("TYPE类型不能为空！");
				return res;
			}
			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}
			CouponOrder couponOrder = new CouponOrder();
			if ("0".equals(req.getString("userType"))) {// 本人订单
				couponOrder.setMember(member);
			} else {// 客户订单
				couponOrder.setDataScope(" AND a.uid IN(SELECT id FROM t_member WHERE invite_id='"+req.getString("uid")+"') ");
			}
			if ("1".equals(req.getString("type"))) {// 待付款
				couponOrder.setState("0");
			} else if ("2".equals(req.getString("type"))) {// 待使用
				couponOrder.setState("1");
			} else if ("3".equals(req.getString("type"))) {// 已使用
				couponOrder.setState("2");
			} else if ("4".equals(req.getString("type"))) {// 退款
				couponOrder.setState("4");
			}
			Page<CouponOrder> page = couponOrderService.findPage(new Page<CouponOrder>(req.getPageNo(), req.getPageSize()), couponOrder);
			for (CouponOrder n : page.getList()) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("orderId", n.getId());
				map.put("orderNum", n.getId());
				map.put("status", n.getState());
				map.put("money", n.getMoney());
				map.put("price", n.getPrice());
				map.put("startDate", DateFormatUtil.ISO_ON_DATE_FORMAT.format(n.getStartDate()));
				map.put("endDate", DateFormatUtil.ISO_ON_DATE_FORMAT.format(n.getEndDate()));
				map.put("shopId", n.getShop().getId());
				map.put("shopName", n.getShop().getTitle());
				map.put("integral", n.getPoint());
				dataList.add(map);
			}
			res.setTotalPage(page.getTotalPage());
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 商品上架/下架
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/productShelf")
	@ResponseBody
	public ResJson productShelf(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("操作失败！");
		try {
			if (StringUtils.isBlank(req.getString("id"))) {
				res.setResultNote("商品ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("type"))) {
				res.setResultNote("TYPE类型不能为空！");
				return res;
			}
			Product product = productService.get(req.getString("id"));
			if (product == null) {
				res.setResultNote("该商品不存在！");
				return res;
			}
			if ("0".equals(req.getString("type"))) {// 下架
				product.setState("1");
			} else {// 上架
				product.setState("0");
			}
			productService.save(product);
			res.setResult("0");
			res.setResultNote("操作成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 店铺管理信息
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/factoryInfo")
	@ResponseBody
	public ResJson factoryInfo(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		try {
			if (StringUtils.isBlank(req.getString("factoryId"))) {
				res.setResultNote("商家ID不能为空！");
				return res;
			}
			Store store = storeService.get(req.getString("factoryId"));
			if (store == null) {
				res.setResultNote("该商家不存在！");
				return res;
			}
			String daySales = "0";// 今日销售额
			int daySalesVolume = 0;// 今日销量
			List<Map<String,Object>> list = productOrderService.executeSelectSql("SELECT IFNULL(SUM(c.amount),0) amount, IFNULL(SUM(b.qty),0) qty FROM t_product_order a JOIN t_order_item b ON a.id = b.order_id JOIN t_product_sku c ON b.sku_id = c.id WHERE a.store_id = '"+store.getId()+"' AND a.state IN ('1','2','3','4') AND DATE(a.create_date) = CURDATE()");
			if (list != null && !list.isEmpty()) {
				Map<String, Object> map = list.get(0);
				if (map.get("amount") != null) {
					daySales = map.get("amount").toString();
				}
				if (map.get("qty") != null) {
					daySalesVolume = Integer.parseInt(map.get("qty").toString());
				}
			}
			/*ProductOrder productOrder = new ProductOrder();
			productOrder.setStore(store);
			productOrder.setDataScope("TO_DAYS(a.pay_date) = TO_DAYS(now())");
			List<ProductOrder> oList = productOrderService.findList(productOrder);

			if (oList != null && oList.size() > 0) {
				for (ProductOrder o : oList) {
					daySales = daySales.add(new BigDecimal(o.getAmount()));
					OrderItem orderItem = new OrderItem();
					orderItem.setOrder(o);
					List<OrderItem> oiList = orderItemMapper.findList(orderItem);
					if (oiList != null && oiList.size() > 0) {
						for (OrderItem oi : oiList) {
							daySalesVolume = daySalesVolume + oi.getQty();
						}
					}
				}
			}*/
			res.put("daySales", daySales);
			res.put("daySalesVolume", daySalesVolume);

			String totalSales = "0";// 累计销售额
			int totalSalesVolume = 0;// 累计销量
			// 商品数量
			String productCount = productService.executeGetSql("SELECT COUNT(*) FROM t_product a WHERE a.store_id = '"+store.getId()+"' " + (StringUtils.isNotBlank(req.getString("startTime")) && StringUtils.isNotBlank(req.getString("endTime")) ? " AND a.create_date BETWEEN '"+req.getString("startTime")+"' AND '"+req.getString("endTime")+"'" : "")).toString();

			// 累计客户
			String totalClient = productOrderService.executeGetSql("SELECT COUNT(DISTINCT uid) FROM t_product_order WHERE store_id = '"+store.getId()+"' " + (StringUtils.isNotBlank(req.getString("startTime")) && StringUtils.isNotBlank(req.getString("endTime")) ? " AND create_date BETWEEN '"+req.getString("startTime")+"' AND '"+req.getString("endTime")+"'" : "")+" UNION SELECT uid FROM t_group_order WHERE store_id = '"+store.getId()+"' "  + (StringUtils.isNotBlank(req.getString("startTime")) && StringUtils.isNotBlank(req.getString("endTime")) ? " AND create_date BETWEEN '"+req.getString("startTime")+"' AND '"+req.getString("endTime")+"'" : "")).toString();

			/*ProductOrder productOrder1 = new ProductOrder();
			productOrder1.setStore(store);
			if (StringUtils.isNotBlank(req.getString("startTime")) && StringUtils.isNotBlank(req.getString("endTime"))) {
				productOrder1.setDataScope("a.pay_date BETWEEN " + req.getString("startTime") + " AND " + req.getString("endTime") + "");
			}
			List<ProductOrder> oList1 = productOrderService.findList(productOrder);

			if (oList1 != null && oList1.size() > 0) {
				for (ProductOrder o : oList1) {
					totalSales = totalSales.add(new BigDecimal(o.getAmount()));
					OrderItem orderItem = new OrderItem();
					orderItem.setOrder(o);
					List<OrderItem> oiList = orderItemMapper.findList(orderItem);
					if (oiList != null && oiList.size() > 0) {
						for (OrderItem oi : oiList) {
							totalSalesVolume = totalSalesVolume + oi.getQty();
						}
					}
				}
			}*/
			List<Map<String,Object>> list1 = productOrderService.executeSelectSql("SELECT IFNULL(SUM(c.amount),0) amount, IFNULL(SUM(b.qty),0) qty FROM t_product_order a JOIN t_order_item b ON a.id = b.order_id JOIN t_product_sku c ON b.sku_id = c.id WHERE a.store_id = '"+store.getId()+"' AND a.state IN ('1','2','3','4') " + (StringUtils.isNotBlank(req.getString("startTime")) && StringUtils.isNotBlank(req.getString("endTime")) ? " AND a.create_date BETWEEN '"+req.getString("startTime")+"' AND '"+req.getString("endTime")+"'" : ""));
			if (list1 != null && !list1.isEmpty()) {
				Map<String, Object> map = list1.get(0);
				if (map.get("amount") != null) {
					totalSales = map.get("amount").toString();
				}
				if (map.get("qty") != null) {
					totalSalesVolume = Integer.parseInt(map.get("qty").toString());
				}
			}
			res.put("totalSales", totalSales);
			res.put("totalSalesVolume", totalSalesVolume);
			// 商品数量
			/*Product product = new Product();
			product.setStore(store);
			product.setAuditState("1");
			if (StringUtils.isNotBlank(req.getString("startTime"))
					&& StringUtils.isNotBlank(req.getString("endTime"))) {
				product.setDataScope(
						"a.audit_date BETWEEN " + req.getString("startTime") + " AND " + req.getString("endTime") + "");
			}
			List<Product> pList = productService.findList(product);
			res.put("productCount", pList.size());*/
			res.put("productCount", productCount);
			// 累计客户（暂时写死）
			res.put("totalClient", totalClient);
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 云店订单列表
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/cloudOrderList")
	@ResponseBody
	public ResJson cloudOrderList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		List<Map<String, Object>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("userType"))) {
				res.setResultNote("用户类型不能为空！");
				return res;
			}
			/*if (StringUtils.isBlank(req.getString("type"))) {
				res.setResultNote("TYPE类型不能为空！");
				return res;
			}*/

			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}

			// 获取订单各类型数量
			// 订单状态0-待付，1-待发，2-待收，3-待评，4-已评，5-取消，6-退款中，7-已退款
			String count0 = "0";// 待付订单数量
			String count1 = "0";// 待发订单数量
			String count2 = "0";// 待收订单数量
			String count3 = "0";// 待评价订单数量
			String count4 = "0";// 已完成订单数量
			String count5 = "0";// 取消订单数量
			String count6 = "0";// 售后订单数量
			List<Map<String,Object>> list = productOrderService.executeSelectSql("SELECT a.state state,COUNT(*) count FROM t_product_order a WHERE "+("0".equals(req.getString("userType")) ? "a.uid = '"+member.getId()+"' " : " a.uid IN (SELECT id FROM t_member WHERE invite_id='"+req.getString("uid")+"')")+" GROUP BY a.state ");
			if (list != null && !list.isEmpty()) {
				for (Map<String, Object> map : list) {
					String state = map.get("state").toString();
					if ("0".equals(state)) {
						count0 = map.get("count").toString();
					} else if ("1".equals(state)) {
						count1 = map.get("count").toString();
					} else if ("2".equals(state)) {
						count2 = map.get("count").toString();
					} else if ("3".equals(state)) {
						count3 = map.get("count").toString();
					} else if ("4".equals(state)) {
						count4 = map.get("count").toString();
					} else if ("5".equals(state)) {
						count5 = map.get("count").toString();
					} else if ("6".equals(state)) {
						count6 = map.get("count").toString();
					}
				}
			}
			res.put("count0", count0);
			res.put("count1", count1);
			res.put("count2", count2);
			res.put("count3", count3);
			res.put("count4", count4);
			res.put("count5", count5);
			res.put("count6", count6);

			ProductOrder productOrder = new ProductOrder();
			String dataScope = "";
			if ("0".equals(req.getString("userType"))) {// 本人订单
				productOrder.setMember(member);
			} else {// 客户订单
				dataScope += " AND a.uid IN(SELECT id FROM t_member WHERE invite_id='"+req.getString("uid")+"') ";
			}
			/*if ("6".equals(req.getString("type"))) {
				dataScope += " AND (a.state = '6' OR a.state = '7') ";
			} else {
				productOrder.setState(req.getString("type"));
			}*/
			productOrder.setState(req.getString("type"));
			productOrder.setDataScope(dataScope);
			/*if ("1".equals(req.getString("type"))) {// 待付款
				productOrder.setState("0");
			} else if ("2".equals(req.getString("type"))) {// 待使用
				productOrder.setState("1");
			} else if ("3".equals(req.getString("type"))) {// 已使用
				productOrder.setState("2");
			} else if ("4".equals(req.getString("type"))) {// 退款
				productOrder.setState("4");
			}*/
			Page<ProductOrder> page = productOrderService.findPage(new Page<ProductOrder>(req.getPageNo(), req.getPageSize()), productOrder);
			for (ProductOrder n : page.getList()) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("orderId", n.getId());
				map.put("shopName", n.getStore().getTitle());
				map.put("orderNum", n.getId());
				map.put("status", n.getState());
				map.put("ishot",n.getIsHot());
				map.put("isProxy", n.getProxyType());
				map.put("payMoney", n.getAmount());
				map.put("daimai", n.getDaimai() != null && StringUtils.isNotBlank(n.getDaimai().getId()) ? "1" : "0");
				List<Map<String, Object>> productList = new ArrayList<Map<String, Object>>();
				OrderItem orderItem = new OrderItem();
				orderItem.setOrder(n);
				// 订单商品列表
				List<OrderItem> opList = orderItemMapper.findList(orderItem);
				if (opList != null && opList.size() > 0) {
					for (OrderItem op : opList) {
						Map<String, Object> map1 = new HashMap<String, Object>();
						map1.put("productId", op.getProductId());
						map1.put("productName", op.getProductTitle());
						map1.put("productCode", op.getProductCode());
						map1.put("coverImage", getRealImage(op.getProductIcon()));
						map1.put("specification", op.getSkuName());
						map1.put("integral", op.getPoint());
						map1.put("price", op.getPrice());
						map1.put("count", op.getQty());
						map1.put("isdl", op.getIsDl());
						map1.put("isyg", op.getIsYg());
						if("1".equals(n.getIsHot())){
							map1.put("ishot", "1");
						}else{
							map1.put("ishot", "0");
						}
						productList.add(map1);
					}
				}
				map.put("productList", productList);
				dataList.add(map);
			}
			res.setTotalPage(page.getTotalPage());
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 厂家入驻
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/factoryEnter")
	@ResponseBody
	public ResJson factoryEnter(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("申请失败！");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("factoryName"))) {
				res.setResultNote("请输入厂家名称！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("project"))) {
				res.setResultNote("请输入主营项目！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("contactName"))) {
				res.setResultNote("请输入联系人姓名！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("contactTele"))) {
				res.setResultNote("请输入联系人电话！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("contractorTele"))) {
				res.setResultNote("请输入签约人电话！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("businessLicense"))) {
				res.setResultNote("请上传营业执照！");
				return res;
			}
			JSONArray jsonArray = req.getJSONArray("idCardImage");
			if (jsonArray == null || jsonArray.isEmpty()) {
				res.setResultNote("请上传身份证照！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("payMoney"))) {
				res.setResultNote("支付金额不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("state"))) {
				res.setResultNote("选择的支付类型不能为空！");
				return res;
			}
			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}
			// 调用三方会员系统判断签约人

			List<WohuiEntity> entityList = Lists.newArrayList();
			entityList.add(new WohuiEntity("phone", req.getString("contractorTele")));
			JSONObject object = WohuiUtils.send(WohuiUtils.GetUInfoByPhone, entityList);
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("签约人信息错误（或者该账号没有签约权限）");
				return res;
			}
			JSONArray array = object.getJSONArray("data");
			JSONObject obj = array.getJSONObject(0);
			String guid = obj.getString("C_GUID");
			String IsCFM="0";
			if (StringUtils.isNotBlank(obj.getString("C_Roles"))) {
				String[] roles = obj.getString("C_Roles").split(",");
				List<String> rolesList = Arrays.asList(roles);
				if (rolesList.contains("C2F创客") || rolesList.contains("云店铺") ) {
					IsCFM = "1";
				}
			}
			if(!"1".equals(IsCFM)){
				res.setResultNote("该签约人不是C2F创客,请重新选择签约人！");
				return res;
			}
			entityList.clear();
			// 判断状态
			Store store = storeService.findUniqueByProperty("uid", member.getId());
			if (store != null) {
				if ("1".equals(store.getAuditState())) {
					res.setResultNote("申请审核中");
					return res;
				}
				if ("2".equals(store.getAuditState())) {
					res.setResultNote("您已成为厂家店铺，请勿重复申请");
					return res;
				}
				if ("3".equals(store.getAuditState())) {
					store.setAuditState("1");
				}
				if ("4".equals(store.getAuditState())) {
					store.setAuditState("0");
				}
			} else {
				store = new Store();
				store.setIsNewRecord(true);
				store.setId(OrderNumPrefix.storeOrder + IdGen.getOrderNo());
				store.setMember(member);
				store.setStoreCode("GYS" + RandomStringUtils.randomNumeric(7));
				store.setProductCode("CM" + RandomStringUtils.randomNumeric(5));
				store.setState("0");
				store.setAuditState("0");
				store.setBalance("0");
				store.setHuitian("1");
				store.setFreight("0");
			}

			store.setTitle(req.getString("factoryName"));
			store.setCategory(req.getString("project"));
			store.setUsername(req.getString("contactName"));
			store.setPhone(req.getString("contactTele"));
			store.setInvite(new Member(guid));
			store.setInvitePhone(req.getString("contractorTele"));
			store.setInviteName(obj.getString("C_RealName"));
			store.setLicence(req.getString("businessLicense"));
			store.setIdcard(StringUtils.join(jsonArray, "|"));
			JSONArray otherImageList = req.getJSONArray("otherImage");
			if (otherImageList != null && !otherImageList.isEmpty()) {
				store.setOthers(StringUtils.join(otherImageList, "|"));
			}
			store.setPaymoney("0");
			store.setAmount(req.getString("payMoney"));
			store.setXhtype("1");

			storeService.save(store);
			res.put("orderNum", "0".equals(store.getAuditState()) ? store.getId() : "");
			res.put("amount", req.getString("payMoney"));
			res.put("state", req.getString("state"));
			res.setResult("0");
			res.setResultNote("申请成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 修改登录密码
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/wohuiLogout")
	@ResponseBody
	public ResJson wohuiLogout(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("注销账号失败！");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("LoginPwd"))) {
				res.setResultNote("请输入密码！");
				return res;
			}
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getUid()));
			list.add(new WohuiEntity("LoginPwd", req.getString("LoginPwd")));
			JSONObject object = WohuiUtils.send(WohuiUtils.Logout, list);
			if ("0000".equals(object.getString("respCode"))) {
				res.setResult("0");
				res.setResultNote("您已成功申请注销账号！");
			} else {
				res.setResultNote(object.getString("respMsg"));
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 修改登录密码
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/editPassword")
	@ResponseBody
	public ResJson editPassword(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("修改失败！");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("oldPassword"))) {
				res.setResultNote("请输入原密码！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("newPassword"))) {
				res.setResultNote("请输入新密码！");
				return res;
			}

			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getUid()));
			list.add(new WohuiEntity("OldPwd", req.getString("oldPassword")));
			list.add(new WohuiEntity("NewPwd", req.getString("newPassword")));
			list.add(new WohuiEntity("Action", "LOGIN"));
			JSONObject object = WohuiUtils.send(WohuiUtils.UpdatePwd, list);
			if ("0000".equals(object.getString("respCode"))) {
				res.setResult("0");
				res.setResultNote("修改成功");
			} else {
				res.setResultNote(object.getString("respMsg"));
			}

			/*Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}
			if (!req.getString("oldPassword").equals(member.getPassword())) {
				res.setResultNote("原密码输入不正确！");
				return res;
			}
			member.setPassword(req.getString("newPassword"));
			memberService.save(member);
			res.setResult("0");
			res.setResultNote("修改成功！");*/
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 提交店铺简介
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/submitShopDesc")
	@ResponseBody
	public ResJson submitShopDesc(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("提交失败！");
		try {
			if (StringUtils.isBlank(req.getString("shopId"))) {
				res.setResultNote("商家ID不能为空！");
				return res;
			}
			Shop shop = shopService.get(req.getString("shopId"));
			if (shop == null) {
				res.setResultNote("该商家不存在！");
				return res;
			}
			if (StringUtils.isNotBlank(req.getString("desc"))) {
				shop.setContent(req.getString("desc"));
			}
			if (StringUtils.isNotBlank(req.getString("images"))) {
				shop.setImages(req.getString("images"));
			}
			shop.setShowState("0");
			shopService.save(shop);
			res.setResult("0");
			res.setResultNote("提交成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 根据guid判断是否有大于50铜板的订单
	 * @return
	 */
	@PostMapping("/IsMyuidorderpoint")
	@ResponseBody
	public String IsMyuidorderpoint(String uid) {
			String cretime="2020-05-05 00:00:00";
			String state = "0";
			if (!isBlank(uid)) {
				List<Map<String,Object>> list = productOrderService.executeSelectSql("SELECT i.point,i.qty FROM t_product_order p LEFT JOIN t_order_item i on p.id=i.order_id where p.uid='"+uid+"' AND (i.point/i.qty)>='50.00' AND p.state>0 AND p.state<5 AND p.create_date>='"+cretime+"'");
				if (list != null && !list.isEmpty()) {
					state = "1";
				}
			}
		return state;
	}
	/**
	 * 会员接口获取流量分红数据
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/personalHBnum")
	@ResponseBody
	public ResJson personalHBnum(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		try {
//			List<WohuiEntity> entityList = Lists.newArrayList();
//			entityList.add(new WohuiEntity("UGUID", req.getUid()));
//			JSONObject object = WohuiUtils.send(WohuiUtils.GetUInfoByGUID, entityList);
//			if (!"0000".equals(object.getString("respCode"))) {
//				res.setResultNote(object.getString("respMsg"));
//				return res;
//			}
//			JSONArray data = object.getJSONArray("data");
//			JSONObject obj = data.getJSONObject(0);
//
//			res.put("XFTBSum",obj.getDoubleValue("C_XFTBSum"));//2020.05.03后已消费铜板
//			res.put("TXCardNum",obj.getIntValue("C_TXNumSum"));//已拓新会员数量//返回的名字不一样
//			res.put("XHGoodsSum",obj.getIntValue("C_XHGoodsSum"));//已选货数量
//			//需要传的分红份数
//			String xfnumbercop="1";//可获得消费流量红包分红份数
//			String txnumbercop="1";//可获得拓新流量红包分红份数
//			String xhnumbercop="1";//可获得选货流量红包分红份数
//			String XFHBNum=obj.getString("C_XFHBNum");//已获得消费流量红包分红份数
//			String TXHBNum=obj.getString("C_TXHBNum");//已获得拓新流量红包分红份数
//			String XHHBNum=obj.getString("C_XHHBNum");//已获得选货流量红包分红份数
//
//			res.put("XFHBNum",XFHBNum);
//			res.put("TXHBNum",TXHBNum);
//			res.put("XHHBNum",XHHBNum);
//			//			C_TXNumUse //拓新会员数量-已使用数
//			//			C_TXNumSum  //拓新会员数量-总数
//			//			C_XFTBUse//消费铜板-已使用数
//			//			C_XFTBSum //消费铜板-总数
//
//			SimpleDateFormat dftime = new SimpleDateFormat("yyyy/MM/dd H:mm:ss");
//			Date JuneTime=dftime.parse("2020/6/01 00:00:00");
//			Date JulyTime=dftime.parse("2020/7/01 00:00:00");
//			Date AugTime=dftime.parse("2020/8/01 00:00:00");
//			Date SeptTime=dftime.parse("2020/9/01 00:00:00");
//			Date OctTime=dftime.parse("2020/10/01 00:00:00");
//			Date now = new Date();//当前时间
//			Double xfnumber = 100.00;//消费计算数
//			int txnumber = 15;//拓新计算数
//
////			if(now.getTime() >= JuneTime.getTime()){
////				xfnumber = 25.00;
////				txnumber = 15;
////
////			}
//			if(now.getTime() >= JulyTime.getTime()){
//				xfnumber = 100.00;
//				txnumber = 15;
//			}
//			if(now.getTime() >= AugTime.getTime()){
//				txnumber = 15;
//			}
////			if(now.getTime() >= SeptTime.getTime()){
////				txnumber = 25;
////			}
////			if(now.getTime() >= OctTime.getTime()){
////				txnumber = 30;
////			}
//
//			//			消费当前值 0
////			消费流量
//			DecimalFormat df = new DecimalFormat("#.0000");
//
//			Double C_XFTBUse =obj.getDoubleValue("C_XFTBUse");
//			Double xftargetGVTB= C_XFTBUse + xfnumber;//消费流量消费目标值
//			String xfwneedGVTB= df.format(xftargetGVTB -obj.getDoubleValue("C_XFTBSum"));//消费流量需再消费值
//			//			消费当前值 0
////			拓新流量
//			double txtargetGVTB=obj.getIntValue("C_TXNumUse")+txnumber;//拓新流量消费目标值
//			double txwneedGVTB=txtargetGVTB-obj.getIntValue("C_TXNumSum");//拓新流量需再消费值
//
//			//			消费当前值 0
////			选货流量
//			double xhtargetGVTB=Math.floor(obj.getIntValue("C_XHGoodsSum")/50)*50+50;//选货消费目标值
////			double xhtargetGVTB=Math.floor(obj.getIntValue("C_XHGoodsSum")/10)*10+10;//选货消费目标值
//			double xhwneedGVTB=xhtargetGVTB-obj.getIntValue("C_XHGoodsSum");//选货需再消费值
//			double aa = ((xhtargetGVTB/50) * 5)-Integer.parseInt(XHHBNum);
//			DecimalFormat df2 = new DecimalFormat("#");
////			xhnumbercop = df2.format(Math.ceil(xhwneedGVTB/10));
//			xhnumbercop = df2.format(Math.ceil(aa));
//			res.put("xfnumbercop",xfnumbercop);
//			res.put("txnumbercop",txnumbercop);
//			res.put("xhnumbercop",xhnumbercop);
//
//			res.put("xftargetGVTB",df.format(xftargetGVTB));
//			res.put("xfwneedGVTB",xfwneedGVTB);
//
//			res.put("txtargetGVTB",txtargetGVTB);
//			res.put("txwneedGVTB",txwneedGVTB);
//
//			res.put("xhtargetGVTB",xhtargetGVTB);
//			res.put("xhwneedGVTB",xhwneedGVTB);
			res.setResult("0");
			res.setResultNote("提交成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 个人中心信息
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/personalCenterInfo")
	@ResponseBody
	public ResJson personalCenterInfo(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("请先登录");
				return res;
			}
			List<WohuiEntity> entityList = Lists.newArrayList();
			entityList.add(new WohuiEntity("UGUID", req.getUid()));
			JSONObject object = WohuiUtils.send(WohuiUtils.GetUInfoByGUID, entityList);
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote(object.getString("respMsg"));
				return res;
			}
			JSONArray data = object.getJSONArray("data");
			JSONObject obj = data.getJSONObject(0);
			List<WohuiEntity> entityList2 = Lists.newArrayList();
			entityList2.add(new WohuiEntity("CardGUID", req.getUid()));
			JSONObject object2 = WohuiUtils.send(WohuiUtils.BPPrizeGetStatus, entityList2);
			String  BP_BPQStatus="0";
			String  BP_LYJJStatus="0";
			if (!"0000".equals(object2.getString("respCode"))) {

			}else{
				JSONArray data6 = object2.getJSONArray("data");
				JSONObject obj6 = data6.getJSONObject(0);
				BP_BPQStatus=obj6.getString("BP_BPQStatus");
				BP_LYJJStatus=obj6.getString("BP_LYJJStatus");
			}
			//2021/5/25
			//爆品的次数
			res.put("BP_BPQStatus",BP_BPQStatus);
			//2021/5/25后旅游基金的次数
			res.put("BP_LYJJStatus",BP_LYJJStatus);

			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}


			res.put("userIcon", getRealImage(member.getIcon()));
			res.put("nickName", member.getNickname());
			res.put("phoneNum", member.getPhone());
			String txopenidstate ="0";//未绑定
			if( StringUtils.isNotBlank(member.getTxopenid())){
				txopenidstate ="1";
			}
			res.put("txopenidstate", txopenidstate);
			//判断是否被别人注册
			String regGuid=obj.getString("C_Sender");
			String isReg="";
			if (StringUtils.isNotBlank(obj.getString("C_Roles"))) {
				SimpleDateFormat sdf =   new SimpleDateFormat("yyyy/MM/dd H:mm:ss");
				Long sxTime;//上线时间
				sxTime = Long.parseLong(String.valueOf(sdf.parse("2019/12/26 0:00:00").getTime()/1000));
				SimpleDateFormat regSdf = new SimpleDateFormat("yyyy/MM/dd H:mm:ss");
				Long regTime;//注册时间
				regTime = Long.parseLong(String.valueOf(regSdf.parse(obj.getString("C_RegTime")).getTime()/1000));
				if("35278AE6B4E14F1F9582937C5C836453".equals(regGuid)){
					if(regTime>=sxTime){
						isReg="0";
					}else{
						isReg="1";
					}
				}else{
					isReg="1";
				}
			}else{
				isReg="0";
			}
			res.put("isBindReg", isReg);

			//2018/8/8
			//注册会员数量
			res.put("ZTCardNum",obj.getString("C_ZTCardNum"));
			//省
			res.put("Province",obj.getString("C_Province"));
			//市
			res.put("City",obj.getString("C_City"));
			//县
			res.put("District",obj.getString("C_District"));

			//新增
			//上月待结算
			res.put("LMJSBonus",obj.getString("C_LMJSBonus"));
			//本月待结算
			res.put("TMJSBonus",obj.getString("C_TMJSBonus"));

			//注册人在用微信号
			res.put("ZTWeChat",obj.getString("C_ZTWeChat"));
			//注册人在用手机号
			res.put("ZTUsePhone",obj.getString("C_ZTUsePhone"));

			//本人在用微信号
			res.put("WeChat",obj.getString("C_WeChat"));
			//本人在用手机号
			res.put("UsePhone",obj.getString("C_UsePhone"));

			//成为单品代理时间
			res.put("PCATime",obj.getString("C_PCATime"));
			//会员增选产品总数
			res.put("GoodsSum",obj.getString("C_GoodsSum"));

			// 从会员系统取数据，目前暂时写死
			res.put("availableCoupons", obj.getString("C_Consume_Bonus"));
			res.put("thisMonth", obj.getString("C_TMBonus"));
			res.put("lastMonth", obj.getString("C_LMBonus"));
			//是否是贫困户
			res.put("IsPoor", obj.getString("C_IsPoor"));
			//是否贫困户二维码
			res.put("IsHPQR", obj.getString("C_IsHPQR"));
			//云店选获权数量
			res.put("XHQNum", obj.getIntValue("C_XHQNum"));

			//获得的旅游基金
			res.put("TravelFunds", obj.getDoubleValue("C_TravelFunds"));
			//砍一刀开始时间
			res.put("KYDStartTime", obj.getString("C_KYDStartTime"));
			//砍一刀结束时间
			res.put("KYDEndTime", obj.getString("C_KYDEndTime"));
			//爆品购物券
			res.put("BPQ", obj.getDoubleValue("C_BPQ"));
			//新增有效会员数
			res.put("ZTOKNumNew", obj.getIntValue("C_ZTOKNumNew"));

			//C2F创客开通时间
			res.put("CFMTime", obj.getString("C_CFMTime"));
			//直推C2F创客数量
			res.put("ZTCFMNum", obj.getIntValue("C_ZTCFMNum"));
			//本月消费次数
			res.put("TMNum", obj.getIntValue("C_TMNum"));
			//C2F优选专区消费的铜板
			res.put("C2FYXTB", obj.getDoubleValue("C_C2FYXTB"));
			//C2F 星级( 3：王牌，0：无星级)
			res.put("CFMStar", obj.getIntValue("C_CFMStar"));
			//新增注册单品代理数
			res.put("ZTPCANum", obj.getIntValue("C_ZTPCANum"));
			//单品代理类型 （ 0 未申请单品代理，10 老单品代理，20 新单品代理）
			res.put("PCAType", obj.getIntValue("C_PCAType"));

			//销售惠康优品数量
			res.put("HKYDSaleNum", obj.getDoubleValue("C_HKYDSaleNum"));
			//惠康云店分
			res.put("HKYDScore", obj.getIntValue("C_HKYDScore"));
			//2021/9/03
			//鬼谷回春堂购物券
			res.put("PSSGQ", obj.getDoubleValue("C_PSSGQ"));
			//血德平购物券
			res.put("PSSXQ", obj.getDoubleValue("C_PSSXQ"));

			//可申请县区平台代理次数
			res.put("CanCFDMNum", "0");

            //消费券金额   2022.03.04 新增
            res.put("XFQ", obj.getDoubleValue("C_XFQ"));
            //消费券冻结金额   2022.04.07 新增
            res.put("XFQFreeze", obj.getDoubleValue("C_XFQFreeze"));
            //产品专属券-可用  2022.05.29 新增
            res.put("ZSQCan", obj.getDoubleValue("C_ZSQ"));

			//可代理进货的产品类型集合   2022.04.30 新增
			res.put("BHRebuy", obj.getString("C_BHRebuy"));
			// 	是否购买过产品优惠券(VIP)   2022.06.02 新增
			res.put("BHIsVIP", obj.getString("C_BHIsVIP"));

			// 	可授权单品代理数量   2022.07.30 新增
			res.put("PCANumTCGive", obj.getString("C_PCANumTCGive"));
			// 	大健康-是否购买套餐价订单   2022.07.30 新增
			res.put("BHIsTC", obj.getString("C_BHIsTC"));
			// 	大健康-已签到天数   2022.07.30 新增
			res.put("BHSignNum", obj.getString("C_BHSignNum"));
			// 	大健康-可签到天数   2022.07.30 新增
			res.put("BHSignMax", obj.getString("C_BHSignMax"));
			// 	云店-待入账   2022.09.14 新增
			res.put("YDBonus", obj.getString("C_YDBonus"));
			// 	真实姓名   2022.10.19 新增
			res.put("RealName", obj.getString("C_RealName"));

			// 	状态(正常 = 10, 锁定 = 20,冻结 = 21,注销 = 30)
			res.put("Status", obj.getString("C_Status"));

			String IsDPA = "0";// 是否为单品代理
			String IsSupplier = "0";// 是否为供应商
			String IsCFM  = "0";// 是否 C2F创客
			String IsNFH  = "0";// 是否 全国厂家总店
			String isCFDM  = "0";// 是否 县区平台代理
			String isHKQY  = "0";// 是否 惠康区域代理
			if (StringUtils.isNotBlank(obj.getString("C_Roles"))) {
				String[] roles = obj.getString("C_Roles").split(",");
				List<String> rolesList = Arrays.asList(roles);
				if (rolesList.contains("单品代理")) {
					IsDPA = "1";
				}
				if (rolesList.contains("供应商")) {
					IsSupplier = "1";
				}
				if (rolesList.contains("C2F创客") || rolesList.contains("云店铺") ) {
					IsCFM = "1";
				}
				if (rolesList.contains("全国厂家总店")) {
					IsNFH = "1";
				}
				if (rolesList.contains("县区平台代理")) {
					isCFDM = "1";
				}
				if (rolesList.contains("惠康区域代理")) {
					isHKQY = "1";
				}
			}
			res.put("IsNFH",IsNFH);
			res.put("IsCFM",IsCFM);
			res.put("IsDPA", IsDPA);
			res.put("IsSupplier", IsSupplier);
			String  Suppliertype ="";
			if("1".equals(IsSupplier)){
				List<WohuiEntity> entityListgys = Lists.newArrayList();
				entityListgys.add(new WohuiEntity("CardGUID", req.getUid()));
				JSONObject objectgys = WohuiUtils.send(WohuiUtils.GetSupplier, entityListgys);
				if (!"0000".equals(objectgys.getString("respCode"))) {
				}else{
					JSONArray datagys = objectgys.getJSONArray("data");
					JSONObject objgys = datagys.getJSONObject(0);
					Suppliertype=objgys.getString("S_Type");
				}
			}
			res.put("Suppliertype", Suppliertype);
			//新加是否隐藏身份判断
			String isDisDPA = "0";// 是否显示单品代理
			String isDisPTC = "0";// 是否显示申请产品周转中心(全部）
			String isDisHKQYA = "0";// 是否显示申请惠康区域
			String isDisBKA = "0";// 是否显示板块代理
			String isDisKYD = "0";// 是否显示砍一刀
			String isDisPTA = "0";// 是否显示平台代理，
			String isDisRebuy = "0";// 是否显示复购的按钮，0-隐藏，1-显示
			String isDisBHRebuy = "0";// 是否显示代理进货的按钮，0-隐藏，1-显示
			String isDisXDPRebuy = "0";// 是否显示血德平复购的按钮，0-隐藏，1-显示
			String isDisBPQBuy = "0";// 是否显示 爆品购物券兑换的按钮，0-隐藏，1-显示
			String RebuyType = "3";//申请复购的商品类型 3默认不符合 0//单复购 1 //代理自用
            String isDisCFDM = "0";//是否可以申请县区平台代理 0-隐藏，1-显示
            String isDisXFQ = "1";//是否显示购买消费券 0-隐藏，1-显示
			String isDisXFQIsLimit = "0";//消费券是否限制只能在云店铺专区使用 0-隐藏，1-显示
			if("True".equals(obj.getString("C_CFDMIsCan"))){
				isDisCFDM = "1";
			}
			if("True".equals(obj.getString("C_XFQIsLimit"))){
				isDisXFQIsLimit = "1";
			}
			String CFDMTips  = "";//县区平台代理提示
			//县区平台代理提示
			if (StringUtils.isNotBlank(obj.getString("C_CFDMOpenTime")) && "1".equals(isCFDM)) {
				SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd H:mm:ss");
				Date CFDMOpenTime=df.parse(obj.getString("C_CFDMOpenTime"));
				//获得当前月的时间
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd H:mm:ss");
				//获取当前月最后一天
				Calendar rightNow = Calendar.getInstance();//当前月份
				int nowday = rightNow.get(Calendar.DAY_OF_MONTH);//当月几号
//				rightNow.setTime(CFDMOpenTime);
				rightNow.set(Calendar.DAY_OF_MONTH, rightNow.getActualMaximum(Calendar.DAY_OF_MONTH));
				rightNow.set(Calendar.HOUR_OF_DAY, 23);
				rightNow.set(Calendar.MINUTE, 59);
				rightNow.set(Calendar.SECOND, 59);
				rightNow.set(Calendar.DATE, obj.getIntValue("C_CFDMCheckDay"));
				if(nowday > obj.getIntValue("C_CFDMCheckDay")) {//当前号>考核日。
					rightNow.add(Calendar.MONTH, 1);
				}
				SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
				Calendar rightCFDMOpen = Calendar.getInstance();//当前月份
				rightCFDMOpen.setTime(CFDMOpenTime);
				rightCFDMOpen.add(Calendar.MONTH, 1);
				if(!rightCFDMOpen.before(new Date())){
					rightNow.add(Calendar.MONTH, 1);
				}
//				String cfdmymd=ymd.format(CFDMOpenTime);
//				String datemymd=ymd.format(new Date());
//				if(cfdmymd.equals(datemymd)){
//					rightNow.add(Calendar.MONTH, 1);
//				}
				Date CFDMEndTime = rightNow.getTime();
				Calendar cfdmdate = Calendar.getInstance();//县区平台代理月份
				cfdmdate.setTime(CFDMOpenTime);
				int cfdmday = cfdmdate.get(Calendar.DAY_OF_MONTH);//当月几号

//				cfdmdate.set(Calendar.DAY_OF_MONTH, cfdmdate.getActualMaximum(Calendar.DAY_OF_MONTH));
//				cfdmdate.set(Calendar.MINUTE, 59);
//				cfdmdate.set(Calendar.SECOND, 59);
				if(cfdmday >= 29) {//县区平台代理开通号>=29。
					cfdmdate.add(Calendar.MONTH, 7);
					cfdmdate.set(Calendar.HOUR_OF_DAY, 1);
				}else{
					cfdmdate.add(Calendar.MONTH, 6);
					cfdmdate.set(Calendar.HOUR_OF_DAY, obj.getIntValue("C_CFDMCheckDay"));
				}
				cfdmdate.set(Calendar.HOUR_OF_DAY, 23);
				cfdmdate.set(Calendar.MINUTE, 59);
				cfdmdate.set(Calendar.SECOND, 59);
				Calendar addsixcfdmdate = Calendar.getInstance();//县区平台代理月份
				addsixcfdmdate.setTime(CFDMOpenTime);
				addsixcfdmdate.add(Calendar.MONTH, 6);
				if(new Date().before(addsixcfdmdate.getTime())){//当前时间<开通+6个月。
					CFDMTips="恭喜您成为县区平台代理。您的考核日为每月<font color='#FF0000'>"+obj.getString("C_CFDMCheckDay")+"</font>号。您应在"+format.format(CFDMEndTime)+"之前完成消费"+obj.getString("C_CFDMCheckMoney")+"元（已消费：<font color='#FF0000'>"+obj.getString("C_CFDMTMMoney")+"</font>元)并在"+format.format(cfdmdate.getTime())+"之前社群新增会员100名（已新增：<font color='#FF0000'>"+obj.getString("C_CFDMCheckNum")+"</font>名)，否则将影响您县区平台代理相关权益。";
					if(StringUtils.isNotBlank(obj.getString("C_Roles")) && obj.getIntValue("C_CFDMType") == 20){
						CFDMTips="恭喜您成为县区平台代理。您的考核日为每月<font color='#FF0000'>"+obj.getString("C_CFDMCheckDay")+"</font>号。您应在"+format.format(cfdmdate.getTime())+"之前社群新增会员100名（已新增：<font color='#FF0000'>"+obj.getString("C_CFDMCheckNum")+"</font>名)，否则将影响您县区平台代理相关权益。";
					}
				}else{
					rightNow.add(Calendar.MONTH, -1);
					CFDMTips="恭喜您成为县区平台代理。您的考核日为每月<font color='#FF0000'>"+obj.getString("C_CFDMCheckDay")+"</font>号。您应在"+format.format(CFDMEndTime)+"之前完成消费"+obj.getString("C_CFDMCheckMoney")+"元（已消费：<font color='#FF0000'>"+obj.getString("C_CFDMTMMoney")+"</font>元),否则将影响您县区平台代理相关权益。";
				}
			}
			res.put("CFDMTips",CFDMTips);
			String CFMTips  = "";//云店铺提示
			//县区平台代理提示
			if ("1".equals(IsCFM)) {
				SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd H:mm:ss");
				Date CFMOpenTime=df.parse(obj.getString("C_CFMTime"));
				Date standTime=df.parse("2022/08/02 00:00:00");
				if(CFMOpenTime.before(standTime) && "10".equals(obj.getIntValue("C_CFMType"))){
					CFMOpenTime=df.parse("2022/08/02 00:00:10");
				}
				//获得当前月的时间
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd H:mm:ss");
				//获取当前月最后一天
				Calendar rightNow = Calendar.getInstance();//当前月份
				int nowday = rightNow.get(Calendar.DAY_OF_MONTH);//当月几号
				rightNow.set(Calendar.DAY_OF_MONTH, rightNow.getActualMaximum(Calendar.DAY_OF_MONTH));
				rightNow.set(Calendar.HOUR_OF_DAY, 23);
				rightNow.set(Calendar.MINUTE, 59);
				rightNow.set(Calendar.SECOND, 59);
				rightNow.set(Calendar.DATE, obj.getIntValue("C_CFMCheckDay"));
				if(nowday > obj.getIntValue("C_CFMCheckDay")) {//当前号>考核日。
					rightNow.add(Calendar.MONTH, 1);
				}

				Calendar rightCFMOpen = Calendar.getInstance();//当前月份
				rightCFMOpen.setTime(CFMOpenTime);
				rightCFMOpen.add(Calendar.MONTH, 1);
				Date cetime=rightNow.getTime();
				Date rigtime = rightCFMOpen.getTime();
				Date datetime = new Date();
				if(!rightCFMOpen.getTime().before(new Date())){
					rightNow.add(Calendar.MONTH, 1);
				}
				Date rigtime1 = rightCFMOpen.getTime();
                Date cetime1=rightNow.getTime();
				Date EndTime=format.parse("2099-12-31 23:59:59");
				Date CFMEndTime = rightNow.getTime();
//				if("20".equals(obj.getIntValue("C_CFMType"))){//C_CFMType int 云店铺类型(10 老云店铺-永久有效，20 新云店铺-需要考核)
					CFMTips="恭喜您成功开通小店。您的考核日为每月<font color='#FF0000'>"+obj.getString("C_CFMCheckDay")+"</font>号。您应在"+format.format(CFMEndTime)+"之前完成销售100铜板(已销售：<font color='#FF0000'>"+obj.getString("C_CFMSaleTMTB")+"</font>)以免影响您的小店正常营业。";
//				}
			}
			res.put("CFMTips",CFMTips);

			//C_IsRebuyA  399复购  C_IsRebuyB代理自用C_IsRebuyB

//			if("True".equals(obj.getString("C_IsRebuyA")) && "True".equals(obj.getString("C_IsRebuyB"))){ //复购和代理自用
//				RebuyType = "2";
//				isDisRebuy = "1";
//			}else if("True".equals(obj.getString("C_IsRebuyA")) && "False".equals(obj.getString("C_IsRebuyB"))){//单复购
//					RebuyType = "0";
//					isDisRebuy = "1";
//			}else if("False".equals(obj.getString("C_IsRebuyA")) && "True".equals(obj.getString("C_IsRebuyB"))){//代理自用
//					RebuyType = "1";
//					isDisRebuy = "1";
//			}
			//
			if (StringUtils.isNotBlank(obj.getString("C_BHRebuy"))) {
				isDisBHRebuy = "1";
			}
			//血德平复购显示
			if("True".equals(obj.getString("C_IsRebuyC"))){ //复购和代理自用
				isDisXDPRebuy = "1";
			}
			BigDecimal BPQ = new BigDecimal(obj.getString("C_BPQ"));
			BigDecimal BPQprice = new BigDecimal(0);
			if(BPQ.compareTo(BPQprice) > 0){ //BPQ>BPQprice
				isDisBPQBuy="1";
			}
			res.put("RebuyType",RebuyType);
//			//是否显示板块代理
//			if (obj.getIntValue("C_CanBKANum")>0) {
//				isDisBKA="1";
//			}
//			//是否显示板块代理
//			if (obj.getIntValue("C_CanPTANum")>0) {
//				isDisPTA="1";
//			}
			//砍一刀按钮
			if (StringUtils.isNotBlank(obj.getString("C_KYDEndTime"))) {
				SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd H:mm:ss");
				Date KYDTime=df.parse(obj.getString("C_KYDEndTime"));
				if(new Date().before(KYDTime)){
					isDisKYD="1";
				}
			}
//			//产品周转中心(
//			List<Map<String,Object>> list = ptcService.executeSelectSql("SELECT uid,type,id FROM t_ptcapply WHERE uid='"+req.getString("uid")+"' AND state<1 ");
//			if (list != null && !list.isEmpty()) {
//				isDisPTC="1";
//			}
			//惠康区域代理(
//			if("1".equals(isHKQY)){
//				isDisHKQYA="0";
//			}
			List<Map<String,Object>> hkqyalist = hkqyService.executeSelectSql("SELECT uid,type,id FROM t_hkqyapply WHERE uid='"+req.getString("uid")+"' AND state<1 ");
			if (hkqyalist != null && !hkqyalist.isEmpty()) {
				isDisHKQYA="1";
			}
			//单品代理
//			SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd H:mm:ss");
//			Date DPATime=df.parse("2022/01/16 00:00:00");
//			if(new Date().before(DPATime)){//当前时间小于16号
				if(("True".equals(obj.getString("C_PCAIsCan")))){
					isDisDPA="1";
				}
//			}else{
//				BigDecimal YDTB = new BigDecimal(obj.getDoubleValue("C_YDTB"));
//				BigDecimal YDTBNum = new BigDecimal(10);
//				if((!"1".equals(IsDPA)) && (YDTB.compareTo(YDTBNum) > -1 || obj.getIntValue("C_ZTCardNumNew") >= 2) ){
//					 isDisDPA="1";
//				}
//			}
            res.put("isDisXFQ",isDisXFQ);
			res.put("isDisDPA",isDisDPA);
			res.put("isDisCFDM",isDisCFDM);
			res.put("isDisXFQIsLimit",isDisXFQIsLimit);
			res.put("isDisBKA",isDisBKA);
			res.put("isDisPTA",isDisPTA);
			res.put("isDisKYD",isDisKYD);
			res.put("isDisPTC",isDisPTC);
			res.put("isDisHKQYA",isDisHKQYA);
			res.put("isDisRebuy",isDisRebuy);
			res.put("isDisBHRebuy",isDisBHRebuy);
			res.put("isDisXDPRebuy",isDisXDPRebuy);
			res.put("isDisBPQBuy",isDisBPQBuy);


			//新增流量红包
			res.put("XFHBNum",obj.getIntValue("C_XFHBNum"));//消费流量红包分红份数
			res.put("TXHBNum",obj.getIntValue("C_TXHBNum"));//拓新流量红包分红份数
			res.put("XHHBNum",obj.getIntValue("C_XHHBNum"));//选货流量红包分红份数
			if (StringUtils.isNotBlank(member.getWxid())) {
				res.put("isBindWeChat", "1");
			} else {
				res.put("isBindWeChat", "0");
			}
			if (StringUtils.isNotBlank(member.getQqid())) {
				res.put("isBindQQ", "1");
			} else {
				res.put("isBindQQ", "0");
			}
			if (StringUtils.isNotBlank(member.getAliid())) {
				res.put("isBindAlipay", "1");
			} else {
				res.put("isBindAlipay", "0");
			}

			Store store = new Store();
			store.setMember(member);
			List<Store> sList = storeService.findList(store);
			if (sList != null && sList.size() > 0) {
				if ("1".equals(sList.get(0).getState())) {
					res.put("factoryStatus", "4");
				} else {
					if ("0".equals(sList.get(0).getAuditState()) || "4".equals(sList.get(0).getAuditState())) {
						res.put("factoryStatus", "0");
					} else {
						res.put("factoryStatus", sList.get(0).getAuditState());
					}
				}
				res.put("factoryId", sList.get(0).getId());
			} else {
				res.put("factoryStatus", "0");
			}
			Shop shop = new Shop();
			shop.setMember(member);
			List<Shop> sList1 = shopService.findList(shop);
			if (sList1 != null && sList1.size() > 0) {
				if ("1".equals(sList1.get(0).getState())) {
					res.put("shopStatus", "4");
				} else {
					if ("0".equals(sList1.get(0).getAuditState()) || "4".equals(sList1.get(0).getAuditState())) {
						res.put("shopStatus", "0");
					} else {
						res.put("shopStatus", sList1.get(0).getAuditState());
					}
				}
				res.put("shopId", sList1.get(0).getId());
			} else {
				res.put("shopStatus", "0");
			}


			// 未读消息数量
			res.put("msgRead", msgService.executeGetSql("SELECT COUNT(*) FROM t_msg WHERE uid = '"+member.getId()+"' AND state = '0'").toString());
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 修改个人信息
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/updateInfo")
	@ResponseBody
	public ResJson updateInfo(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("修改失败！");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}
			if (StringUtils.isNotBlank(req.getString("userIcon"))) {
				member.setIcon(req.getString("userIcon"));
			}
			if (StringUtils.isNotBlank(req.getString("nickName"))) {
				member.setNickname(req.getString("nickName"));
				if (BadWordUtils.isContaintBadWord(req.getString("nickName"),BadWordUtils.maxMatchType)) {
					Set<String> keywords= BadWordUtils.getBadWord(req.getString("nickName"),BadWordUtils.maxMatchType);
					res.setResult("1");
					res.setResultNote("该昵称存在违规词汇！");
					return res;
				}
			}
			memberService.save(member);
			res.setResult("0");
			res.setResultNote("修改成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 修改真实姓名
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/updateRealName")
	@ResponseBody
	public ResJson updateRealName(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("修改失败！");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("name"))) {
				res.setResultNote("原手机号不能为空！");
				return res;
			}
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getString("uid")));
			list.add(new WohuiEntity("RealName", req.getString("name")));
			JSONObject object = WohuiUtils.send(WohuiUtils.EditRealName, list);
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote(object.getString("respMsg"));
				return res;
			}
			res.setResult("0");
			res.setResultNote("修改成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 修改手机号
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/updatePhoneNum")
	@ResponseBody
	public ResJson updatePhoneNum(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("修改失败！");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("oldPhone"))) {
				res.setResultNote("原手机号不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("phoneNum"))) {
				res.setResultNote("手机号不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("code"))) {
				res.setResultNote("验证码不能为空！");
				return res;
			}
			// 判断验证码
			String captcha = getCaptcha(req.getString("phoneNum"));
			if (!req.getString("code").equals(captcha)) {
				res.setResultNote("验证码错误或已过期");
				return res;
			}
			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}

			// 判断原手机号是否正确
			if (!req.getString("oldPhone").equals(member.getPhone())) {
				res.setResultNote("原手机号错误");
				return res;
			}

			// 判断新手机号是否存在
			if (!"0".equals(memberService.executeGetSql("SELECT COUNT(*) FROM t_member WHERE phone = '"+req.getString("phoneNum")+"'").toString())) {
				res.setResultNote("该手机号已存在");
				return res;
			}

			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", member.getId()));
			list.add(new WohuiEntity("OldPhone", member.getPhone()));
			list.add(new WohuiEntity("NewPhone", req.getString("phoneNum")));
			JSONObject object = WohuiUtils.send(WohuiUtils.EditPhone, list);
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote(object.getString("respMsg"));
				return res;
			}

			member.setPhone(req.getString("phoneNum"));
			memberService.save(member);
			// 清除验证码
			removeCaptcha(req.getString("phoneNum"));
			res.setResult("0");
			res.setResultNote("修改成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 收货地址列表
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/addressList")
	@ResponseBody
	public ResJson addressList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		List<Map<String, Object>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getUid())) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			Address address = new Address();
			address.setMember(new Member(req.getUid()));
			List<Address> aList = addressService.findList(address);
			for (Address n : aList) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", n.getId());
				map.put("name", n.getUsername());
				map.put("telephone", n.getPhone());
				map.put("address", n.getProvince() + n.getCity() + n.getArea());
				map.put("addrDetail", n.getDetails());
				map.put("isDefault", n.getState());
				dataList.add(map);
			}
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	 /**
	 * 收货地址详情
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/addressDetail")
	@ResponseBody
	public ResJson addressDetail(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		try {
			if (StringUtils.isBlank(req.getString("id"))) {
				res.setResultNote("地址ID不能为空！");
				return res;
			}
			Address address = addressService.get(req.getString("id"));
			if (address == null) {
				res.setResultNote("该收货地址不存在！");
				return res;
			}
			res.put("name", address.getUsername());
			res.put("telephone", address.getPhone());
			res.put("province", address.getProvince());
			res.put("city", address.getCity());
			res.put("area", address.getArea());
			res.put("addrDetail", address.getDetails());
			res.put("isDefault", address.getState());
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 删除地址
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/delAddress")
	@ResponseBody
	public ResJson delAddress(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("删除失败！");
		try {
			if (StringUtils.isBlank(req.getString("id"))) {
				res.setResultNote("地址ID不能为空！");
				return res;
			}
			Address address = addressService.get(req.getString("id"));
			if (address == null) {
				res.setResultNote("该收货地址不存在！");
				return res;
			}
			addressService.delete(address);
			res.setResult("0");
			res.setResultNote("删除成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 设置默认地址
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/setDefaultAddr")
	@ResponseBody
	public ResJson setDefaultAddr(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("设置失败！");
		try {
			if (StringUtils.isBlank(req.getString("id"))) {
				res.setResultNote("地址ID不能为空！");
				return res;
			}
			Address address = addressService.get(req.getString("id"));
			if (address == null) {
				res.setResultNote("该收货地址不存在！");
				return res;
			}
			// 首先重置所有收货地址都不是默认地址
			Address addr = new Address();
			addr.setMember(new Member(address.getMember().getId()));
			addr.setState("1");
			List<Address> aList = addressService.findList(addr);
			if (aList != null && aList.size() > 0) {
				aList.get(0).setState("0");
				addressService.save(aList.get(0));
			}
			// 然后设置默认地址
			address.setState("1");
			addressService.save(address);
			res.setResult("0");
			res.setResultNote("设置成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 添加或编辑地址
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/addOrUpdateAddr")
	@ResponseBody
	public ResJson addOrUpdateAddr(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("操作失败！");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}
			if (StringUtils.isNotBlank(req.getString("id"))) {// 编辑收货地址
				Address a = addressService.get(req.getString("id"));
				if (a == null) {
					res.setResultNote("该地址不存在！");
					return res;
				}
				if (StringUtils.isNotBlank(req.getString("name"))) {
					a.setUsername(req.getString("name"));
				}
				if (StringUtils.isNotBlank(req.getString("telephone"))) {
					a.setPhone(req.getString("telephone"));
				}
				if (StringUtils.isNotBlank(req.getString("province"))) {
					a.setProvince(req.getString("province"));
				}
				if (StringUtils.isNotBlank(req.getString("city"))) {
					a.setCity(req.getString("city"));
				}
				if (StringUtils.isNotBlank(req.getString("area"))) {
					a.setArea(req.getString("area"));
				}
				if (StringUtils.isNotBlank(req.getString("addrDetail"))) {
					a.setDetails(req.getString("addrDetail"));
				}
				a.setUpdateDate(new Date());
				addressService.save(a);
			} else {// 添加收货地址
				if (StringUtils.isBlank(req.getString("name"))) {
					res.setResultNote("请输入收货人姓名！");
					return res;
				}
				if (StringUtils.isBlank(req.getString("telephone"))) {
					res.setResultNote("请输入收货人电话！");
					return res;
				}
				if (StringUtils.isBlank(req.getString("province"))) {
					res.setResultNote("请选择省份！");
					return res;
				}
				if (StringUtils.isBlank(req.getString("city"))) {
					res.setResultNote("请选择城市！");
					return res;
				}
				if (StringUtils.isBlank(req.getString("area"))) {
					res.setResultNote("请选择区县！");
					return res;
				}
				if (StringUtils.isBlank(req.getString("addrDetail"))) {
					res.setResultNote("请输入详细地址！");
					return res;
				}
				Address a = new Address();
				a.setIsNewRecord(true);
				a.setId(IdGen.uuid());
				a.setMember(member);
				a.setUsername(req.getString("name"));
				a.setPhone(req.getString("telephone"));
				a.setProvince(req.getString("province"));
				a.setCity(req.getString("city"));
				a.setArea(req.getString("area"));
				a.setDetails(req.getString("addrDetail"));
				// 查询是否存在默认地址
				Address addr = new Address();
				addr.setMember(new Member(req.getString("uid")));
				addr.setState("1");
				List<Address> aList = addressService.findList(addr);
				if (aList != null && aList.size() > 0) {
					a.setState("0");
				} else {
					a.setState("1");
				}
				a.setCreateDate(new Date());
				a.setUpdateDate(new Date());
				addressService.save(a);
			}
			res.setResult("0");
			res.setResultNote("操作成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 绑定微信，QQ，支付宝
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/bindThirdParty")
	@ResponseBody
	public ResJson bindThirdParty(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("绑定失败！");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("type"))) {
				res.setResultNote("TYPE类型不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("openId"))) {
				res.setResultNote("OPENID不能为空！");
				return res;
			}
			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}
			// 判断三方ID是否存在

			if ("0".equals(req.getString("type"))) {// 微信
				String count = memberService.executeGetSql("SELECT COUNT(*) FROM t_member WHERE wxid = '"+req.getString("openId")+"'").toString();
				if (!"0".equals(count)) {
					res.setResultNote("该微信号已被绑定");
					return res;
				}
				member.setWxid(req.getString("openId"));
			} else if ("1".equals(req.getString("type"))) {// 支付宝
				String count = memberService.executeGetSql("SELECT COUNT(*) FROM t_member WHERE aliid = '"+req.getString("openId")+"'").toString();
				if (!"0".equals(count)) {
					res.setResultNote("该支付宝号已被绑定");
					return res;
				}
				member.setAliid(req.getString("openId"));
			} else {// QQ
				String count = memberService.executeGetSql("SELECT COUNT(*) FROM t_member WHERE qqid = '"+req.getString("openId")+"'").toString();
				if (!"0".equals(count)) {
					res.setResultNote("该QQ号已被绑定");
					return res;
				}
				member.setQqid(req.getString("openId"));
			}
			memberService.save(member);
			res.setResult("0");
			res.setResultNote("绑定成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 解绑微信，支付宝，QQ
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/untiedThirdParty")
	@ResponseBody
	public ResJson untiedThirdParty(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("解绑失败！");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("type"))) {
				res.setResultNote("TYPE类型不能为空！");
				return res;
			}
			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}
			if ("0".equals(req.getString("type"))) {// 微信
				member.setWxid(null);
			} else if ("1".equals(req.getString("type"))) {// 支付宝
				member.setAliid(null);
			} else {// QQ
				member.setQqid(null);
			}
			memberService.save(member);
			res.setResult("0");
			res.setResultNote("解绑成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 退出登录
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/logout")
	@ResponseBody
	public ResJson logout(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("退出失败！");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			/*Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}
			member.setToken(null);
			memberService.save(member);*/
			memberService.executeUpdateSql("UPDATE t_member SET token = NULL WHERE id = '"+req.getUid()+"'");
			res.setResult("0");
			res.setResultNote("退出成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 购物车列表
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/cartList")
	@ResponseBody
	public ResJson cartList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		List<Map<String, Object>> dataList = Lists.newArrayList();// 结果集
		Map<String, String> shopMap = Maps.newLinkedHashMap();// 商家集
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			/*Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}*/
			// 商家组
			Cart paramObj = new Cart();
			paramObj.setMember(new Member(req.getUid()));
			//paramObj.setFenzu("0");
			if (StringUtils.isNotBlank(req.getString("cartId"))) {
				paramObj.setDataScope(" AND FIND_IN_SET(a.id,'"+req.getString("cartId")+"') ");
			}
			List<Cart> cartList = cartService.findList(paramObj);
			for (Cart cart : cartList) {
				shopMap.put(cart.getStore().getId(), cart.getStore().getTitle());
			}

			for (String key : shopMap.keySet()) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("shopId", key);
				map.put("shopName", shopMap.get(key));
				List<Map<String, Object>> productList = Lists.newArrayList();
				for (Cart cart : cartList) {
					if (key.equals(cart.getStore().getId())) {
						Map<String, Object> product = Maps.newHashMap();
						product.put("cartId", cart.getId());
						product.put("productId", cart.getProduct().getId());
						product.put("coverImage", getRealImage(cart.getProduct().getIcon()));
						product.put("productCode", cart.getProduct().getCode());
						product.put("productName", cart.getProduct().getTitle());
						product.put("specification", cart.getSku().getTitle());
						product.put("integral", cart.getProduct().getPoint());
						product.put("point", cart.getSku().getPoint());
						product.put("giftprice", cart.getProduct().getGiftprice());
						product.put("isteprice", cart.getProduct().getIsteprice());
						product.put("postCouponPrice", cart.getSku().getPrice());
						product.put("stock", cart.getSku().getStock());
						product.put("count", cart.getQty());
						product.put("ishot", cart.getProduct().getIsHot());
						product.put("oldPrice", cart.getSku().getOldPrice());
						product.put("discount", cart.getSku().getDiscount());
						product.put("isbd", cart.getProduct().getIsbd());
						productList.add(product);
					}
				}
				map.put("productList", productList);
				dataList.add(map);
			}
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 删除购物车商品
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/delCart")
	@ResponseBody
	public ResJson delCart(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("删除失败！");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("cartIds"))) {
				res.setResultNote("请选择要删除的商品！");
				return res;
			}
			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}
			String[] cartIds = req.getString("cartIds").split(",");
			for (String cartId : cartIds) {
				Cart cart = cartService.get(cartId);
				if (cart != null) {
					cartService.delete(cart);
				}
			}
			res.setResult("0");
			res.setResultNote("删除成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 修改购物车
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/editCart")
	@ResponseBody
	public ResJson editCart(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("修改失败！");
		try {
			if (StringUtils.isBlank(req.getString("cartId"))) {
				res.setResultNote("购物车ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("count"))) {
				res.setResultNote("数量不能为空！");
				return res;
			}
			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}
			Cart cart = cartService.get(req.getString("cartId"));
			if(cart == null){
				res.setResultNote("该购物车商品不存在");
				return res;
			}
			cart.setQty(req.getIntValue("count"));
			cartService.save(cart);

			res.setResult("0");
			res.setResultNote("修改成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 申请单品代理、批发云店铺
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/applySingleProxy")
	@ResponseBody
	public ResJson applySingleProxy(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("申请失败！");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("role"))) {
				res.setResultNote("用户身份不能为空！");
				return res;
			}
			if ("10".equals(req.getString("role"))) {
				res.setResultNote("请更新APP到最新版本！");
				return res;
			}
			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}
//			BigDecimal Price = new BigDecimal(req.getString("fee"));
//			if (Price.compareTo(BigDecimal.ZERO) < 0) {
//				res.setResultNote("申请金额不能小于0！");
//				return res;
//			}
			String orderId = OrderNumPrefix.proxyOrder + IdGen.getOrderNo();
			ProxyOrder o = new ProxyOrder();
			o.setIsNewRecord(true);
			o.setId(orderId);
			o.setCode(req.getString("role"));
			o.setMember(member);
			o.setTrade_type("");
			o.setType("0");
			o.setPrice("6.00");
			o.setState("1");
			proxyOrderService.insert(o);
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", o.getMember().getId()));
			list.add(new WohuiEntity("OrderNO", o.getId()));
			list.add(new WohuiEntity("Fee", o.getPrice()));
			JSONObject object = WohuiUtils.send(WohuiUtils.PCAOpen, list);
			if (!"0000".equals(object.getString("respCode"))) {
				logger.error("开通代理失败：" + object.getString("respMsg"));
				res.setResultNote("开通代理失败："+object.getString("respMsg"));
				return res;
			}
			res.put("orderNum", o.getId());
			res.put("amount", "0.00");
			res.setResult("0");
			res.setResultNote("申请成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
			res.setResultNote(e.getMessage());
		}
		return res;
	}
	/**
	 * 申请零售云店铺
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/applyRCSOpen")
	@ResponseBody
	public ResJson applyRCSOpen(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("开通失败！");
		try {
			res.setResultNote("请更新APP到最新版本！");
		} catch (Exception e) {
			logger.error(e.getMessage());
			res.setResultNote(e.getMessage());
		}
		return res;
	}

	/**
	 * 根据用户ID查询购买过的产品编码（申请单品代理中用）
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/findBuyProductByUid")
	@ResponseBody
	public ResJson findBuyProductByUid(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		List<Map<String, Object>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			/*Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}*/
			// 产品类型 0云店 1淘客 2京东 3拼多多
			if ("1".equals(req.getString("type"))) {

			} else if ("2".equals(req.getString("type"))) {

			} else if ("3".equals(req.getString("type"))) {

			} else {
				dataList = productOrderService.executeSelectSql("SELECT a.product_code productCode, a.product_title productName, c.store_code shopCode FROM t_order_item a JOIN t_product_order b ON a.order_id = b.id JOIN t_store c ON b.store_id = c.id WHERE b.uid = '"+req.getUid()+"' AND (b.state = '3' OR b.state = '4') GROUP BY a.product_id ORDER BY a.create_date DESC");
			}
			/*ProductOrder productOrder = new ProductOrder();
			productOrder.setMember(new Member(req.getUid()));
			//productOrder.setProxyType("0");
			productOrder.setState("3,4");
			productOrder.setFenzu("0");
			List<ProductOrder> aList = productOrderService.findList(productOrder);
			for (ProductOrder n : aList) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("productCode", n.getCode());
				dataList.add(map);
			}*/
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 申请赠送单品代理
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/applyGiftProxy")
	@ResponseBody
	public ResJson applyGiftProxy(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("接口作废");
		try {
			/*if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("isDaimai"))) {
				res.setResultNote("请选择是否代买！");
				return res;
			}
			if ("1".equals(req.getString("isDaimai"))) {
				if (StringUtils.isBlank(req.getString("telephone"))) {
					res.setResultNote("请输入手机号！");
					return res;
				}
			}
			if (StringUtils.isBlank(req.getString("type"))) {
				res.setResultNote("请选择申请类型！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("province"))) {
				res.setResultNote("请选择省份！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("city"))) {
				res.setResultNote("请选择城市！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("area"))) {
				res.setResultNote("请选择区县！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("productCode"))) {
				res.setResultNote("请选择产品编码！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("serviceFee"))) {
				res.setResultNote("服务费用不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("payMoney"))) {
				res.setResultNote("支付金额不能为空！");
				return res;
			}
			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}
			ProxyOrder o = new ProxyOrder();
			o.setIsNewRecord(true);
			o.setId(OrderNumPrefix.proxyOrder+IdGen.getOrderNo());
			if ("1".equals(req.getString("isDaimai"))) {// 代买
				Member m = memberService.findUniqueByProperty("phone", req.getString("telephone"));
				o.setMember(m);
			} else {
				o.setMember(member);
			}
			if ("0".equals(req.getString("type"))) {// 签约赠送
				o.setType("2");
			} else {// 分享赠送
				o.setType("3");
			}
			o.setProvince(req.getString("province"));
			o.setCity(req.getString("city"));
			o.setArea(req.getString("area"));
			o.setCode(req.getString("productCode"));
			o.setPrice(req.getString("payMoney"));
			o.setCreateDate(new Date());
			o.setState("0");
			proxyOrderService.save(o);
			res.put("orderNum", o.getId());
			res.put("amount", o.getPrice());
			res.setResult("0");
			res.setResultNote("申请成功！");*/
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 支付方式列表
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/payMethodList")
	@ResponseBody
	public ResJson payMethodList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		List<Map<String, Object>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getUid())) {
				res.setResultNote("请先登录");
				return res;
			}

			PayType payType = new PayType();
			payType.setState("0");
			List<PayType> aList = payTypeService.findList(payType);
			for (PayType n : aList) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("type", n.getType());
				dataList.add(map);
			}
			// 获取用户平台购物券和商城购物券
			double pt = 0d;// 平台
			double sc = 0d;// 商城
			// 调用三方会员系统
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("UGUID", req.getUid()));
			JSONObject object = WohuiUtils.send(WohuiUtils.GetUInfoByGUID, list);
			if ("0000".equals(object.getString("respCode"))) {
				JSONArray jsonArray = object.getJSONArray("data");
				if (jsonArray != null && !jsonArray.isEmpty()) {
					JSONObject obj = jsonArray.getJSONObject(0);
					pt = obj.getDoubleValue("C_Consume_Bonus");
					sc = obj.getDoubleValue("C_XFB");
				}
			}

			res.put("ptAmount", pt);
			res.put("scAmount", sc);
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 实体店铺信息
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/shopInfo")
	@ResponseBody
	public ResJson shopInfo(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		try {
			if (StringUtils.isBlank(req.getString("shopId"))) {
				res.setResultNote("商家ID不能为空！");
				return res;
			}
			Shop shop = shopService.get(req.getString("shopId"));
			if (shop == null) {
				res.setResultNote("该商家不存在！");
				return res;
			}
			// 今日销售额
			String daySales = "0";
			String daySalesVolume = "0";
			List<Map<String,Object>> list = couponOrderService.executeSelectSql("SELECT IFNULL(SUM(b.amount),0) amount,COUNT(a.id) count FROM t_coupon_order a JOIN t_shop_coupon b ON a.coupon_id = b.id WHERE a.shop_id = '"+shop.getId()+"' AND a.state IN ('1','2') AND DATE(a.create_date) = CURDATE()");
			if (list != null && !list.isEmpty()) {
				Map<String, Object> map = list.get(0);
				if (map.get("amount") != null) {
					daySales = map.get("amount").toString();
				}
				if (map.get("count") != null) {
					daySalesVolume = map.get("count").toString();
				}
			}
			/*CouponOrder couponOrder = new CouponOrder();
			couponOrder.setShop(shop);
			couponOrder.setDataScope("TO_DAYS(a.pay_date) = TO_DAYS(now())");
			List<CouponOrder> oList = couponOrderService.findList(couponOrder);
			BigDecimal daySales = BigDecimal.ZERO;// 今日销售额
			if (oList != null && oList.size() > 0) {
				for (CouponOrder o : oList) {
					daySales = daySales.add(new BigDecimal(o.getPrice()));
				}
			}*/
			res.put("daySales", daySales);
			res.put("daySalesVolume", daySalesVolume);

			// 累计销售额
			/*CouponOrder couponOrder1 = new CouponOrder();
			couponOrder1.setShop(shop);
			if (StringUtils.isNotBlank(req.getString("startTime")) && StringUtils.isNotBlank(req.getString("endTime"))) {
				couponOrder1.setDataScope("a.pay_date BETWEEN '" + req.getString("startTime") + "' AND '" + req.getString("endTime") + "'");
			}
			List<CouponOrder> oList1 = couponOrderService.findList(couponOrder1);
			BigDecimal totalSales = BigDecimal.ZERO;// 累计销售额
			if (oList1 != null && oList1.size() > 0) {
				for (CouponOrder o : oList1) {
					totalSales = totalSales.add(new BigDecimal(o.getPrice()));
				}
			}*/
			String totalSales = "0";
			String totalSalesVolume = "0";
			List<Map<String,Object>> list1 = couponOrderService.executeSelectSql("SELECT IFNULL(SUM(b.amount),0) amount,COUNT(a.id) count FROM t_coupon_order a JOIN t_shop_coupon b ON a.coupon_id = b.id WHERE a.shop_id = '"+shop.getId()+"' AND a.state IN ('1','2') " + (StringUtils.isNotBlank(req.getString("startTime")) && StringUtils.isNotBlank(req.getString("endTime")) ? " AND a.create_date BETWEEN '"+req.getString("startTime")+"' AND '"+req.getString("endTime")+"'" : ""));
			if (list1 != null && !list1.isEmpty()) {
				Map<String, Object> map = list1.get(0);
				if (map.get("amount") != null) {
					totalSales = map.get("amount").toString();
				}
				if (map.get("count") != null) {
					totalSalesVolume = map.get("count").toString();
				}
			}

			res.put("totalSales", totalSales);
			res.put("totalSalesVolume", totalSalesVolume);
			// 商品数量
			/*ShopCoupon shopCoupon = new ShopCoupon();
			shopCoupon.setShop(shop);
			shopCoupon.setAudit("1");
			if (StringUtils.isNotBlank(req.getString("startTime"))
					&& StringUtils.isNotBlank(req.getString("endTime"))) {
				shopCoupon.setDataScope(
						"a.audit_date BETWEEN " + req.getString("startTime") + " AND " + req.getString("endTime") + "");
			}
			List<ShopCoupon> pList = shopCouponService.findList(shopCoupon);*/
			String productCount = shopCouponService.executeGetSql("SELECT COUNT(*) FROM t_shop_coupon a WHERE a.shop_id = '"+shop.getId()+"'" + (StringUtils.isNotBlank(req.getString("startTime")) && StringUtils.isNotBlank(req.getString("endTime")) ? " AND a.create_date BETWEEN '"+req.getString("startTime")+"' AND '"+req.getString("endTime")+"'" : "")).toString();

			res.put("productCount", productCount);
			// 累计客户
			String totalClient = couponOrderService.executeGetSql("SELECT COUNT(DISTINCT a.uid) FROM t_coupon_order a WHERE a.shop_id = '"+shop.getId()+"'" + (StringUtils.isNotBlank(req.getString("startTime")) && StringUtils.isNotBlank(req.getString("endTime")) ? " AND a.create_date BETWEEN '"+req.getString("startTime")+"' AND '"+req.getString("endTime")+"'" : "")).toString();
			res.put("totalClient", totalClient);
			res.put("balance", shop.getBalance());
			String prop = "0";// 提现费率
			List<CashProp> propList = cashPropService.findList(new CashProp());
			for (CashProp cashProp : propList) {
				if ("2".equals(cashProp.getType())) {
					prop = cashProp.getProp();
					break;
				}
			}
			res.put("prop", prop);
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}


	/**
	 * 提现
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/applyWithdraw")
	@ResponseBody
	public ResJson applyWithdraw(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("申请失败！");
		try {
			if (StringUtils.isBlank(req.getString("shopId"))) {
				res.setResultNote("商家ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("bankName"))) {
				res.setResultNote("请输入银行名称！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("name"))) {
				res.setResultNote("请输入持卡人姓名！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("cardNum"))) {
				res.setResultNote("请输入银行卡号！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("money"))) {
				res.setResultNote("请输入提现金额！");
				return res;
			}

			Shop shop = shopService.get(req.getString("shopId"));
			if (shop == null) {
				res.setResultNote("该实体商家不存在！");
				return res;
			}
			if ((new BigDecimal(shop.getBalance()).compareTo(new BigDecimal(req.getString("money")))) < 0) {
				res.setResultNote("提现金额不能大于账户余额！");
				return res;
			}
			// 手续费
			BigDecimal prop = BigDecimal.ZERO;

			List<CashProp> propList = cashPropService.findList(new CashProp());
			for (CashProp cashProp : propList) {
				if ("2".equals(cashProp.getType())) {
					prop = new BigDecimal(cashProp.getProp());
					break;
				}
			}

			ShopCash sc = new ShopCash();
			sc.setShop(shop);
			sc.setAmount(req.getString("money"));
			sc.setFee(prop.multiply(new BigDecimal(req.getString("money"))).toString());
			sc.setUsername(req.getString("name"));
			sc.setBank(req.getString("bankName"));
			sc.setAccount(req.getString("cardNum"));
			sc.setState("0");
			//shopCashService.save(sc);
			shopCashService.add(sc);

			// 更新商家账户余额
			/*shop.setBalance(new BigDecimal(shop.getBalance()).subtract(new BigDecimal(req.getString("money"))).toString());
			shopService.save(shop);
			if (StringUtils.isNotBlank(sc.getId())) {
				// 向账单插入一条数据
				ShopBill sb = new ShopBill();
				sb.setIsNewRecord(true);
				sb.setId(IdGen.uuid());
				sb.setShop(shop);
				sb.setTitle(req.getString("bankName") + "-"
						+ req.getString("cardNum").substring(req.getString("cardNum").length() - 4));
				sb.setAmount(req.getString("money"));
				sb.setType("0");
				sb.setCreateDate(new Date());
				shopBillService.save(sb);
			}*/
			res.setResult("0");
			res.setResultNote("申请成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 拼团提现
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/ptapplyWithdraw")
	@ResponseBody
	public ResJson ptapplyWithdraw(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("申请失败！");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("团长ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("bankName"))) {
				res.setResultNote("请输入银行名称！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("name"))) {
				res.setResultNote("请输入持卡人姓名！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("cardNum"))) {
				res.setResultNote("请输入银行卡号！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("money"))) {
				res.setResultNote("请输入提现金额！");
				return res;
			}
			Group group = groupService.findUniqueByProperty("uid", req.getString("uid"));
			if (group == null) {
				res.setResultNote("该团长信息不存在！");
				return res;
			}
			if ((new BigDecimal(group.getBalance()).compareTo(new BigDecimal(req.getString("money")))) < 0) {
				res.setResultNote("提现金额不能大于账户余额！");
				return res;
			}
			// 手续费
			BigDecimal prop = BigDecimal.ZERO;

			List<CashProp> propList = cashPropService.findList(new CashProp());
			for (CashProp cashProp : propList) {
				if ("2".equals(cashProp.getType())) {
					prop = new BigDecimal(cashProp.getProp());
					break;
				}
			}
			GroupCash sc = new GroupCash();
			sc.setGroup(group);
			sc.setAmount(req.getString("money"));
			sc.setFee(prop.multiply(new BigDecimal(req.getString("money"))).toString());
			sc.setUsername(req.getString("name"));
			sc.setBank(req.getString("bankName"));
			sc.setAccount(req.getString("cardNum"));
			sc.setState("0");
			groupCashService.add(sc);
			res.setResult("0");
			res.setResultNote("申请成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 根据用户ID查询用户银行卡信息（提现页面用）
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/findBankInfoByUid")
	@ResponseBody
	public ResJson findBankInfoByUid(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		try {
			if (StringUtils.isBlank(req.getString("shopId"))) {
				res.setResultNote("商家ID不能为空！");
				return res;
			}
			Shop shop = shopService.get(req.getString("shopId"));
			if (shop == null) {
				res.setResultNote("该实体商家不存在！");
				return res;
			}
			ShopCash shopCash = new ShopCash();
			shopCash.setShop(shop);
			List<ShopCash> scList = shopCashService.findList(shopCash);
			if (scList != null && scList.size() > 0) {
				res.put("bankName", scList.get(0).getBank());
				res.put("name", scList.get(0).getUsername());
				res.put("cardNum", scList.get(0).getAccount());
			}
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 我的账单列表
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/myBillList")
	@ResponseBody
	public ResJson myBillList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		List<Map<String, Object>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getString("shopId"))) {
				res.setResultNote("商家ID不能为空！");
				return res;
			}
			Shop shop = shopService.get(req.getString("shopId"));
			if (shop == null) {
				res.setResultNote("该实体商家不存在！");
				return res;
			}
			ShopBill shopBill = new ShopBill();
			shopBill.setShop(shop);
			Page<ShopBill> page = shopBillService.findPage(new Page<ShopBill>(req.getPageNo(), req.getPageSize()),
					shopBill);
			for (ShopBill n : page.getList()) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("title", n.getTitle());
				map.put("money", n.getAmount());
				map.put("szType", n.getType());
				map.put("adtime", n.getCreateDate());
				dataList.add(map);
			}
			res.setTotalPage(page.getTotalPage());
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 拼团订单列表
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/myGroupBillList")
	@ResponseBody
	public ResJson myGroupBillList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		List<Map<String, Object>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			Group group = groupService.findUniqueByProperty("uid", req.getString("uid"));
			if (group == null) {
				res.setResultNote("该信息不存在！");
				return res;
			}

			GroupBill groupBill = new GroupBill();
			groupBill.setGroup(group);
			Page<GroupBill> page = groupBillService.findPage(new Page<GroupBill>(req.getPageNo(), req.getPageSize()),
					groupBill);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			for (GroupBill n : page.getList()) {
				Map<String, Object> map = Maps.newHashMap();
//				map.put("order", n.getOrderId());
				map.put("title", n.getTitle());
				map.put("money", n.getAmount());
				map.put("szType", n.getType());
				map.put("adtime", sdf.format(n.getCreateDate()));
				dataList.add(map);
			}
			res.setTotalPage(page.getTotalPage());
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 查询店铺简介（实体店铺中用）
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/findShopDesc")
	@ResponseBody
	public ResJson findShopDesc(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		try {
			if (StringUtils.isBlank(req.getString("shopId"))) {
				res.setResultNote("商家ID不能为空！");
				return res;
			}
			Shop shop = shopService.get(req.getString("shopId"));
			if (shop == null) {
				res.setResultNote("该实体商家不存在！");
				return res;
			}
			res.put("desc", shop.getContent());
			List<String> images = new ArrayList<String>();
			if (StringUtils.isNotBlank(shop.getImages())) {
				for (String img : shop.getImages().split("\\|")) {
					if (StringUtils.isNotBlank(img)) {
						images.add(getRealImage(img));
					}
				}
				/*for (int i = 0; i < shop.getImages().split("\\|").length; i++) {
					images.add(getRealImage(shop.getImages().split("\\|")[i]));
				}*/
			}
			res.put("imageList", images);
			if (StringUtils.isNotBlank(shop.getShowState())) {
				res.put("status", shop.getShowState());
			} else {
				res.put("status", "3");
			}
			if(StringUtils.isBlank(shop.getImages()) && StringUtils.isBlank(shop.getContent()) ){
				res.put("status", "3");
			}
			res.put("audit_state", shop.getAuditState());
			res.put("title", shop.getTitle());
			res.put("phone", shop.getPhone());
			res.put("icon", shop.getIcon());
			res.put("licence", shop.getLicence());
			res.put("others", shop.getOthers());
			res.put("city", shop.getCity());
			res.put("lat", shop.getLat());
			res.put("lon", shop.getLon());
			res.put("address", shop.getAddress());
			res.put("hyrebate", new BigDecimal(10).multiply(new BigDecimal(1).subtract(new BigDecimal(shop.getHyrebate()))).stripTrailingZeros().toPlainString());
			res.put("ptrebate", new BigDecimal(10).multiply(new BigDecimal(1).subtract(new BigDecimal(shop.getPtrebate()))).stripTrailingZeros().toPlainString());
			String point = new BigDecimal(100).multiply(new BigDecimal(shop.getPtrebate())).stripTrailingZeros().toPlainString();
			res.put("yuanpoint", new BigDecimal("0.4").multiply(new BigDecimal(point)).setScale(1, BigDecimal.ROUND_DOWN).toPlainString());
			res.put("reason", shop.getRemarks());
			res.put("uid", shop.getMember().getId());
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 优惠券管理列表（实体商家中用）
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/voucherList")
	@ResponseBody
	public ResJson voucherList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		List<Map<String, Object>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getString("shopId"))) {
				res.setResultNote("商家ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("type"))) {
				res.setResultNote("TYPE类型不能为空！");
				return res;
			}
			Shop shop = shopService.get(req.getString("shopId"));
			if (shop == null) {
				res.setResultNote("该实体商家不存在！");
				return res;
			}
			ShopCoupon shopCoupon = new ShopCoupon();
			shopCoupon.setShop(shop);
			shopCoupon.setState(req.getString("type"));
			//shopCoupon.setAudit("1");
			Page<ShopCoupon> page = shopCouponService.findPage(new Page<ShopCoupon>(req.getPageNo(), req.getPageSize()),
					shopCoupon);
			for (ShopCoupon n : page.getList()) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("voucherId", n.getId());
				map.put("money", n.getMoney());
				map.put("price", n.getPrice());
				map.put("startDate", n.getStartDate());
				map.put("endDate", n.getEndDate());
				map.put("content", n.getContent());
				dataList.add(map);
			}
			res.setTotalPage(page.getTotalPage());
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 添加和编辑优惠券（实体商家用）
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/addOrUpdateVoucher")
	@ResponseBody
	public ResJson addOrUpdateVoucher(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("操作失败！");
		try {
			if (StringUtils.isBlank(req.getString("shopId"))) {
				res.setResultNote("商家ID不能为空！");
				return res;
			}
			Shop shop = shopService.get(req.getString("shopId"));
			if (shop == null) {
				res.setResultNote("该实体商家不存在！");
				return res;
			}
			if (StringUtils.isNotBlank(req.getString("voucherId"))) {// 编辑优惠券
				ShopCoupon a = shopCouponService.get(req.getString("voucherId"));
				if (a == null) {
					res.setResultNote("该优惠券不存在！");
					return res;
				}
				if (!"0".equals(a.getState())) {
					res.setResultNote("优惠券只有在未上架状态才能修改！");
					return res;
				}
				if (StringUtils.isNotBlank(req.getString("price"))) {
					a.setPrice(req.getString("price"));
				}
				if (StringUtils.isNotBlank(req.getString("money"))) {
					a.setMoney(req.getString("money"));
				}
				if (StringUtils.isNotBlank(req.getString("amount"))) {
					a.setAmount(req.getString("amount"));
				}
				if (StringUtils.isNotBlank(req.getString("startDate"))) {
					a.setStartDate(DateUtil.beginOfDate(DateUtils.parseDate(req.getString("startDate"))));
				}
				if (StringUtils.isNotBlank(req.getString("endDate"))) {
					//a.setEndDate(new SimpleDateFormat("yyyy-MM-dd").parse(req.getString("endDate")));
					a.setEndDate(new Date(DateUtil.nextDate(DateUtils.parseDate(req.getString("endDate"))).getTime() - 1000));
				}
				if (StringUtils.isNotBlank(req.getString("content"))) {
					a.setContent(req.getString("content"));
				}
				shopCouponService.save(a);
			} else {// 添加优惠券
				if (StringUtils.isBlank(req.getString("price"))) {
					res.setResultNote("请输入售价！");
					return res;
				}
				if (StringUtils.isBlank(req.getString("money"))) {
					res.setResultNote("请输入抵用金额！");
					return res;
				}
				if (StringUtils.isBlank(req.getString("amount"))) {
					res.setResultNote("请选择结算价！");
					return res;
				}
				if (StringUtils.isBlank(req.getString("startDate"))) {
					res.setResultNote("请选择有效起始时间！");
					return res;
				}
				if (StringUtils.isBlank(req.getString("endDate"))) {
					res.setResultNote("请选择有效截止时间！");
					return res;
				}
				if (StringUtils.isBlank(req.getString("content"))) {
					res.setResultNote("请输入使用规则！");
					return res;
				}
				ShopCoupon a = new ShopCoupon();
				a.setIsNewRecord(true);
				a.setId(IdGen.uuid());
				a.setShop(shop);
				a.setPrice(req.getString("price"));
				a.setMoney(req.getString("money"));
				a.setAmount(req.getString("amount"));
				//a.setStartDate(new SimpleDateFormat("yyyy-MM-dd").parse(req.getString("startDate")));
				//a.setEndDate(new SimpleDateFormat("yyyy-MM-dd").parse(req.getString("endDate")));
				a.setStartDate(DateUtil.beginOfDate(DateUtils.parseDate(req.getString("startDate"))));
				a.setEndDate(new Date(DateUtil.nextDate(DateUtils.parseDate(req.getString("endDate"))).getTime() - 1000));
				a.setContent(req.getString("content"));
				a.setState("0");
				a.setPoint("0");
				a.setAudit("0");
				a.setCode(shop.getCouponCode());
				shopCouponService.save(a);
			}
			res.setResult("0");
			res.setResultNote("操作成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 根据优惠券ID查询优惠券信息（实体商家用）
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/findCouponByVid")
	@ResponseBody
	public ResJson findCouponByVid(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		try {
			if (StringUtils.isBlank(req.getString("voucherId"))) {
				res.setResultNote("优惠券ID不能为空！");
				return res;
			}
			ShopCoupon shopCoupon = shopCouponService.get(req.getString("voucherId"));
			if (shopCoupon == null) {
				res.setResultNote("该优惠券不存在！");
				return res;
			}
			res.put("money", shopCoupon.getMoney());
			res.put("price", shopCoupon.getPrice());
			res.put("amount", shopCoupon.getAmount());
			res.put("startDate", shopCoupon.getStartDate());
			res.put("endDate", shopCoupon.getEndDate());
			res.put("content", shopCoupon.getContent());
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 优惠券订单列表（实体商家中用）
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/voucherOrderList")
	@ResponseBody
	public ResJson voucherOrderList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		List<Map<String, Object>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getString("shopId"))) {
				res.setResultNote("商家ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("type"))) {
				res.setResultNote("TYPE类型不能为空！");
				return res;
			}
			Shop shop = shopService.get(req.getString("shopId"));
			if (shop == null) {
				res.setResultNote("该实体商家不存在！");
				return res;
			}
			CouponOrder couponOrder = new CouponOrder();
			couponOrder.setShop(shop);
			if ("1".equals(req.getString("type"))) {// 待使用
				couponOrder.setState("1");
			} else if ("2".equals(req.getString("type"))) {// 已使用
				couponOrder.setState("2");
			}
			Page<CouponOrder> page = couponOrderService
					.findPage(new Page<CouponOrder>(req.getPageNo(), req.getPageSize()), couponOrder);
			for (CouponOrder n : page.getList()) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("orderId", n.getId());
				map.put("orderNum", n.getId());
				map.put("status", n.getState());
				map.put("money", n.getMoney());
				map.put("price", n.getPrice());
				map.put("startDate", n.getStartDate());
				map.put("endDate", n.getEndDate());
				dataList.add(map);
			}
			res.setTotalPage(page.getTotalPage());
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 优惠券订单详情（实体商家中用）
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/voucherOrderDetail")
	@ResponseBody
	public ResJson voucherOrderDetail(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		try {
			if (StringUtils.isBlank(req.getString("orderId"))) {
				res.setResultNote("订单ID不能为空！");
				return res;
			}
			CouponOrder couponOrder = couponOrderService.get(req.getString("orderId"));
			if (couponOrder == null) {
				res.setResultNote("该订单不存在！");
				return res;
			}
			Member member = memberService.get(couponOrder.getMember());
			if (member != null) {
				res.put("phoneNum", member.getPhone());
			}
			res.put("money", couponOrder.getMoney());
			res.put("price", couponOrder.getPrice());
			res.put("startDate", couponOrder.getStartDate());
			res.put("endDate", couponOrder.getEndDate());
			res.put("payMoney", couponOrder.getPrice());
			res.put("orderNum", couponOrder.getId());
			res.put("adtime", couponOrder.getCreateDate());
			res.put("writeOffTime", couponOrder.getUseDate());
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 商圈订单详情
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/sqOrderDetail")
	@ResponseBody
	public ResJson sqOrderDetail(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		try {
			if (StringUtils.isBlank(req.getString("orderId"))) {
				res.setResultNote("订单ID不能为空！");
				return res;
			}
			CouponOrder couponOrder = couponOrderService.get(req.getString("orderId"));
			if (couponOrder == null) {
				res.setResultNote("该订单不存在！");
				return res;
			}
			/*Shop shop = shopService.get(couponOrder.getShop());
			if (shop != null) {
				res.put("shopId", shop.getId());
				res.put("shopLogo", getRealImage(shop.getIcon()));
				res.put("shopName", shop.getTitle());
				res.put("shopAddr", shop.getAddress());
				res.put("lngAndLat", shop.getLon() + "," + shop.getLat());
				if ("1".equals(shop.getShowState())) {
					res.put("shopDesc", shop.getContent());
					List<String> images = new ArrayList<String>();
					if (StringUtils.isNotBlank(shop.getImages())) {
						for (int i = 0; i < shop.getImages().split("\\|").length; i++) {
							images.add(getRealImage(shop.getImages().split("\\|")[i]));
						}
					}
					res.put("imageList", images.toArray(new String[images.size()]));
				}
			}*/
			res.put("shopId", couponOrder.getShop().getId());
			res.put("shopLogo", getRealImage(couponOrder.getShop().getIcon()));
			res.put("shopName", couponOrder.getShop().getTitle());
			res.put("shopAddr", couponOrder.getShop().getAddress());
			res.put("lngAndLat", couponOrder.getShop().getLon() + "," + couponOrder.getShop().getLat());
			if ("1".equals(couponOrder.getShop().getShowState())) {
				res.put("shopDesc", couponOrder.getShop().getContent());
				List<String> images = new ArrayList<String>();
				if (StringUtils.isNotBlank(couponOrder.getShop().getImages())) {
					for (String img : couponOrder.getShop().getImages().split("\\|")) {
						if (StringUtils.isNotBlank(img)) {
							images.add(getRealImage(img));
						}
					}
				}
				res.put("imageList", images);
			}
			res.put("status", couponOrder.getState());
			res.put("money", couponOrder.getMoney());
			res.put("price", couponOrder.getPrice());
			res.put("startDate", DateFormatUtil.ISO_ON_DATE_FORMAT.format(couponOrder.getStartDate()));
			res.put("endDate", DateFormatUtil.ISO_ON_DATE_FORMAT.format(couponOrder.getEndDate()));
			res.put("integral", couponOrder.getPoint());
			ShopCoupon shopCoupon = shopCouponService.get(couponOrder.getCouponId());
			if (shopCoupon != null) {
				res.put("content", shopCoupon.getContent());
			}
			res.put("payMoney", couponOrder.getPrice());
			res.put("orderNum", couponOrder.getId());
			res.put("phoneNum", couponOrder.getMember().getPhone());
			res.put("adtime", DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(couponOrder.getCreateDate()));
			res.put("refundDate", couponOrder.getRefundDate() != null ? DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(couponOrder.getRefundDate()) : "");
			res.put("cancelReason", couponOrder.getCancelReason());
			res.put("cancelDate", couponOrder.getCancelDate() != null ? DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(couponOrder.getCancelDate()) : "");
			res.put("payTime", couponOrder.getPayDate() != null ? DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(couponOrder.getPayDate()) : "");
			res.put("useTime", couponOrder.getUseDate() != null ? DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(couponOrder.getUseDate()) : "");

			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 原因列表(包含取消订单和申请退款原因)
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/reasonList")
	@ResponseBody
	public ResJson reasonList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		List<Map<String, Object>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getString("type"))) {
				res.setResultNote("TYPE类型不能为空！");
				return res;
			}
			Reason reason = new Reason();
			if ("0".equals(req.getString("type"))) {// 取消原因
				reason.setType("1");
			} else {// 退款原因
				reason.setType("2");
			}
			List<Reason> aList = reasonService.findList(reason);
			for (Reason n : aList) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", n.getId());
				map.put("title", n.getTitle());
				dataList.add(map);
			}
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 云店订单详情
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/ydOrderDetail")
	@ResponseBody
	public ResJson ydOrderDetail(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		try {
			if (StringUtils.isBlank(req.getString("orderId"))) {
				res.setResultNote("订单ID不能为空！");
				return res;
			}
			ProductOrder productOrder = productOrderService.get(req.getString("orderId"));
			if (productOrder == null) {
				res.setResultNote("该订单不存在！");
				return res;
			}
			res.put("status", productOrder.getState());
			res.put("name", productOrder.getUsername());
			res.put("telephone", productOrder.getPhone());
			res.put("address", productOrder.getAddress());
			res.put("shopId", productOrder.getStore().getId());
			res.put("shopName", productOrder.getStore().getTitle());
			res.put("shopTele", productOrder.getStore().getPhone());
			res.put("orderNum", productOrder.getId());
			res.put("totalMoney", productOrder.getPrice());
			res.put("serviceFee", productOrder.getProxyPrice());
			res.put("freight", productOrder.getFreight());
			res.put("giftprice", productOrder.getGiftprice());
			res.put("couponMoney", productOrder.getDiscount());
			res.put("payMoney", productOrder.getAmount());
			res.put("remark", productOrder.getRemarks());
			res.put("adtime", productOrder.getCreateDate() != null ? DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(productOrder.getCreateDate()) : "");
			res.put("payTime", productOrder.getPayDate() != null ? DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(productOrder.getPayDate()) : "");
			res.put("fahuoTime", productOrder.getSendDate() != null ? DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(productOrder.getSendDate()) : "");
			res.put("wanchengTime", productOrder.getCompleteDate() != null ? DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(productOrder.getCompleteDate()) : "");
			res.put("expressCode", productOrder.getExpressCode());
			res.put("expressName", productOrder.getExpressName());
			res.put("expressNo", productOrder.getExpressNo());
			res.put("payType", productOrder.getPayType());
			res.put("ishot", productOrder.getIsHot());
			res.put("receipt", productOrder.getReceipt());
			res.put("daimai", productOrder.getDaimai() != null && StringUtils.isNotBlank(productOrder.getDaimai().getId()) ? "1" : "0");

			OrderRefund orderRefund = new OrderRefund();
			orderRefund.setOrderId(productOrder.getId());
			List<OrderRefund> refundList = orderRefundService.findList(orderRefund);
			if (!refundList.isEmpty()) {
				OrderRefund or = refundList.get(0);
				res.put("refundReason", or.getReason());
				res.put("desc", or.getContent());
				res.put("refundMoney", or.getAmount());
				List<String> images = Lists.newArrayList();
				if (StringUtils.isNotBlank(or.getImages())) {
					for (String image : or.getImages().split("\\|")) {
						if (StringUtils.isNotBlank(image)) {
							images.add(getRealImage(image));
						}
					}
				}
				res.put("imageList", images);
				res.put("applyTime", or.getCreateDate() != null ? DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(or.getCreateDate()) : "");
				res.put("checkTime", or.getAuditDate() != null ? DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(or.getAuditDate()) : "");
			}
			res.put("cancelTime", productOrder.getCancelDate() != null ? DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(productOrder.getCancelDate()) : "");
			res.put("cancelReason", productOrder.getCancelReason());
			List<Map<String, Object>> dataList = Lists.newArrayList();
			//OrderItem orderItem = new OrderItem();
			//orderItem.setOrder(productOrder);
			// 订单商品列表
			//List<OrderItem> opList = orderItemMapper.findList(orderItem);
			//if (opList != null && opList.size() > 0) {
				for (OrderItem op : productOrder.getOrderItemList()) {
					Map<String, Object> map1 = new HashMap<String, Object>();
					map1.put("itemId", op.getId());
					map1.put("productId", op.getProductId());
					map1.put("productName", op.getProductTitle());
					map1.put("coverImage", getRealImage(op.getProductIcon()));
					map1.put("sku", op.getSkuName());
					map1.put("integral", op.getPoint());
					map1.put("price", op.getPrice());
					map1.put("count", op.getQty());
					map1.put("isdl", op.getIsDl());
					map1.put("isyg", op.getIsYg());
					dataList.add(map1);
				}
			//}
			res.put("dataList", dataList);
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 订单取消(未完成)
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/cancelOrder")
	@ResponseBody
	public ResJson cancelOrder(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("取消失败！");
		try {
			if (StringUtils.isBlank(req.getString("orderId"))) {
				res.setResultNote("订单ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("type"))) {
				res.setResultNote("TYPE类型不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("reason"))) {
				res.setResultNote("请选择取消原因！");
				return res;
			}
			if ("0".equals(req.getString("type"))) {// 云店订单
				ProductOrder o = productOrderService.get(req.getString("orderId"));
				if (o == null) {
					res.setResultNote("该订单不存在！");
					return res;
				}
				if (!"0".equals(o.getState())) {
					res.setResultNote("只能取消未付款的订单");
					return res;
				}
				if("1".equals(o.getCftype()) || "2".equals(o.getCftype()) ){
					List<Map<String,Object>> list = ordertaskService.executeSelectSql("SELECT id FROM t_order_task WHERE uid='"+o.getMember().getId()+"' and  orderno='"+o.getId()+"' and state<2 ORDER BY create_date DESC");
					if (list != null && !list.isEmpty()) {
						Ordertask ordertask = new Ordertask();
						ordertask.setId(list.get(0).get("id").toString());
						ordertask.setMember(o.getMember());
						ordertask.setState("3");
						ordertask.setCanceldate(new Date());
						ordertaskService.save(ordertask);
					}
				}
				o.setState("5");
				o.setCancelDate(new Date());
				o.setCancelReason(req.getString("reason"));
				productOrderService.cancel(o);
			} else if ("1".equals(req.getString("type"))) {// 淘客订单

			} else if ("2".equals(req.getString("type"))) {// 拼团订单
				GroupOrder o = groupOrderService.get(req.getString("orderId"));
				if (o == null) {
					res.setResultNote("该订单不存在！");
					return res;
				}
				if (!"0".equals(o.getState())) {
					res.setResultNote("只能取消未付款的订单");
					return res;
				}
				o.setState("5");
				o.setCancelDate(new Date());
				o.setCancelReason(req.getString("reason"));
				groupOrderService.cancel(o);
			} else {// 商圈订单
				CouponOrder o = couponOrderService.get(req.getString("orderId"));
				if (o == null) {
					res.setResultNote("该订单不存在！");
					return res;
				}
				if (!"0".equals(o.getState())) {
					res.setResultNote("只能取消未付款的订单");
					return res;
				}
				o.setState("5");
				o.setCancelDate(new Date());
				o.setCancelReason(req.getString("reason"));
				couponOrderService.save(o);
			}
			res.setResult("0");
			res.setResultNote("取消成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	//拼团流程
	/**
 	* 团长申请
 	* */
	@PostMapping("/shenqing_group")
	@ResponseBody
	public ResJson shenqing_group(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("提交失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("province"))) {
				res.setResultNote("省份不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("city"))) {
				res.setResultNote("城市不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("area"))) {
				res.setResultNote("县区不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("address"))) {
				res.setResultNote("详细地址不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("username"))) {
				res.setResultNote("真实姓名不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("phone"))) {
				res.setResultNote("电话不能为空！");
				return res;
			}
			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}
			String phone =member.getPhone();//姓名手机号
			String name =member.getNickname();
			Group group = groupService.findUniqueByProperty("uid", member.getId());
			if(group==null){
				Group gp=new Group();
				gp.setPhone(req.getString("phone"));
				gp.setUsername(req.getString("username"));
				gp.setProvince(req.getString("province"));
				gp.setCity(req.getString("city"));
				gp.setArea(req.getString("area"));
				gp.setAddress(req.getString("address"));
				gp.setMember(new Member(req.getUid()));
				gp.setState("0");
				gp.setAuditState("2");
				Address a = new Address();
				a.setIsNewRecord(true);
				String Id=IdGen.uuid();
				a.setId(Id);
				a.setMember(member);
				a.setUsername(req.getString("username"));
				a.setPhone(req.getString("phone"));
				a.setProvince(req.getString("province"));
				a.setCity(req.getString("city"));
				a.setArea(req.getString("area"));
				a.setDetails(req.getString("address"));
				// 查询是否存在默认地址2
				Address addr = new Address();
				addr.setMember(new Member(req.getString("uid")));
				addr.setState("1");
				List<Address> aList = addressService.findList(addr);
				if (aList != null && aList.size() > 0) {
					a.setState("0");
				} else {
					a.setState("1");
				}
				a.setCreateDate(new Date());
				a.setUpdateDate(new Date());
				addressService.save(a);
				Address addresspt=addressService.get(Id);
				if(addresspt!=null){
					gp.setAddressId(Id);
				}
				groupService.save(gp);
			}else{
				res.setResultNote("您已经是团长了！");
				res.setResult("1");
				return res;
			}
			res.setResultNote("提交成功");
			res.setResult("0");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 根据uid查询当前团长申请状态
	 * */
	@PostMapping("/shenqingInfo")
	@ResponseBody
	public ResJson shenqingInfo(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}
			Group group = groupService.findUniqueByProperty("uid", member.getId());
			if (group!=null){
				res.put("auditState",group.getAuditState());
				res.put("state",group.getState());
				if(group.getState().equals("1")){
					res.setResultNote("已被冻结！");
					return res;
				}else{
					Map<String, Object> groups = Maps.newHashMap();
					groups.put("Province",group.getProvince());
					groups.put("city",group.getCity());
					groups.put("Area",group.getArea());
					groups.put("phone",group.getPhone());
					groups.put("addres",group.getAddress());
					groups.put("name",group.getUsername());
					groups.put("balance",group.getBalance());
					groups.put("addressId",group.getAddressId());
					res.put("groups",groups);
					res.setResultNote("成功");
				}
			}else{
				res.setResultNote("您还没有申请过团长快去申请吧！");
				res.setResult("1");
				return res;
			}
			res.setResult("0");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	//拼团结束
	/**
	 * 意见反馈
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/feedback")
	@ResponseBody
	public ResJson feedback(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("申请失败！");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("reason"))) {
				res.setResultNote("请选择反馈问题！");
				return res;
			}

			Feedback feedback=new Feedback();
			feedback.setIsNewRecord(true);
			feedback.setId(IdGen.uuid());
			feedback.setMember(new Member(req.getString("uid")));
			feedback.setReason(req.getString("reason"));
			if(StringUtils.isNotBlank(req.getString("desc"))){
				feedback.setContent(req.getString("desc"));
			}
			JSONArray jsonArray = req.getJSONArray("images");
			if(jsonArray != null && !jsonArray.isEmpty()){
				feedback.setImages(StringUtils.join(jsonArray, "|"));
			}
			feedback.setCreateDate(new Date());
			feedback.setState("0");
			feedbackService.save(feedback);
			res.setResult("0");
			res.setResultNote("提交成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 申请退款
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/refundOrder")
	@ResponseBody
	public ResJson refundOrder(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("申请失败！");
		try {
			if (StringUtils.isBlank(req.getString("orderId"))) {
				res.setResultNote("订单ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("type"))) {
				res.setResultNote("TYPE类型不能为空！");
				return res;
			}
			if("0".equals(req.getString("type"))){//云店订单
				if (StringUtils.isBlank(req.getString("reason"))) {
					res.setResultNote("请选择退款原因！");
					return res;
				}
				if (StringUtils.isBlank(req.getString("refundMoney"))) {
					res.setResultNote("请输入退款金额！");
					return res;
				}
				ProductOrder o=productOrderService.get(req.getString("orderId"));
				if(o==null){
					res.setResultNote("该订单不存在！");
					return res;
				}
				if (!"1".equals(o.getState()) && !"2".equals(o.getState())) {
					res.setResultNote("只能申请待发货或待收货的订单");
					return res;
				}
				OrderRefund refund=new OrderRefund();
				refund.setIsNewRecord(true);
				refund.setId(IdGen.uuid());
				refund.setOrderId(o.getId());
				refund.setReason(req.getString("reason"));
				if(StringUtils.isNotBlank(req.getString("desc"))){
					refund.setContent(req.getString("desc"));
				}
				JSONArray jsonArray = req.getJSONArray("images");
				if(jsonArray != null && !jsonArray.isEmpty()){
					refund.setImages(StringUtils.join(jsonArray, "|"));
				}
				refund.setAmount(req.getString("refundMoney"));
				refund.setCreateDate(new Date());
				refund.setState("0");
				refund.setOrderState(o.getState());
				orderRefundService.save(refund);
				//更新订单状态为退款中
				o.setState("6");
				productOrderService.save(o);
			}else if("1".equals(req.getString("type"))){//商圈订单
				CouponOrder o=couponOrderService.get(req.getString("orderId"));
				if(o==null){
					res.setResultNote("该订单不存在！");
					return res;
				}
				if (!"1".equals(o.getState())) {
					res.setResultNote("只能申请未使用的订单");
					return res;
				}
				o.setState("4");
				o.setRefundDate(new Date());
				couponOrderService.refund(o);
			} else if ("2".equals(req.getString("type"))) {// 拼团订单
				if (StringUtils.isBlank(req.getString("reason"))) {
					res.setResultNote("请选择退款原因！");
					return res;
				}
				if (StringUtils.isBlank(req.getString("refundMoney"))) {
					res.setResultNote("请输入退款金额！");
					return res;
				}
				GroupOrder o = groupOrderService.get(req.getString("orderId"));
				if(o==null){
					res.setResultNote("该订单不存在！");
					return res;
				}
				if (!"1".equals(o.getState()) && !"2".equals(o.getState())) {
					res.setResultNote("只能申请待发货或待收货的订单");
					return res;
				}
				GroupRefund refund = new GroupRefund();
				refund.setOrderId(o.getId());
				refund.setReason(req.getString("reason"));
				if(StringUtils.isNotBlank(req.getString("desc"))){
					refund.setContent(req.getString("desc"));
				}
				JSONArray jsonArray = req.getJSONArray("images");
				if(jsonArray != null && !jsonArray.isEmpty()){
					refund.setImages(StringUtils.join(jsonArray, "|"));
				}
				refund.setAmount(req.getString("refundMoney"));
				refund.setCreateDate(new Date());
				refund.setState("0");
				refund.setOrderState(o.getState());
				groupRefundService.save(refund);
				//更新订单状态为退款中
				o.setState("6");
				groupOrderService.save(o);
			}
			res.setResult("0");
			res.setResultNote("提交成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 取消退款申请
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/cancelrefundOrder")
	@ResponseBody
	public ResJson cancelrefundOrder(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("申请失败！");
		try {
			if (StringUtils.isBlank(req.getString("orderId"))) {
				res.setResultNote("订单ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("type"))) {
				res.setResultNote("TYPE类型不能为空！");
				return res;
			}
			if("0".equals(req.getString("type"))){//云店订单
				ProductOrder o=productOrderService.get(req.getString("orderId"));
				if(o==null){
					res.setResultNote("该订单不存在！");
					return res;
				}
				if (!"6".equals(o.getState())) {
					res.setResultNote("只能取消退款中的订单");
					return res;
				}

				List<Map<String, Object>> list = orderRefundService.executeSelectSql("SELECT order_state,id FROM t_order_refund WHERE state=0 and order_id = '" + o.getId() + "' limit 1 ");
				if (list == null && list.isEmpty()) {
					res.setResultNote("该退款申请不存在！");
					return res;
				}
				Map<String, Object> map = list.get(0);
				OrderRefund refund = orderRefundService.get(String.valueOf(map.get("id")));
				refund.setState("2");
				refund.setRemarks("用户取消退款申请");
				orderRefundService.save(refund);
				//更新订单状态为
				o.setState(String.valueOf(map.get("order_state")));
				productOrderService.save(o);
			}else if("1".equals(req.getString("type"))){//商圈订单

			} else if ("2".equals(req.getString("type"))) {// 拼团订单
				GroupOrder o = groupOrderService.get(req.getString("orderId"));
				if(o==null){
					res.setResultNote("该订单不存在！");
					return res;
				}
				if (!"6".equals(o.getState())) {
					res.setResultNote("只能取消退款中的订单");
					return res;
				}
				List<Map<String, Object>> list = groupRefundService.executeSelectSql("SELECT order_state,id FROM t_group_refund WHERE state=0 and order_id = '" + o.getId() + "' limit 1 ");
				if (list == null && list.isEmpty()) {
					res.setResultNote("该退款申请不存在！");
					return res;
				}
				Map<String, Object> map = list.get(0);
				GroupRefund refund = groupRefundService.get(String.valueOf(map.get("id")));
				refund.setState("2");
				refund.setRemarks("用户取消退款申请");
				groupRefundService.save(refund);
				//更新订单状态为
				o.setState("1");
				groupOrderService.save(o);
			}
			res.setResult("0");
			res.setResultNote("提交成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 确认收货
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/confirmShouhuo")
	@ResponseBody
	public ResJson confirmShouhuo(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("确认失败！");
		try {
			if (StringUtils.isBlank(req.getString("orderId"))) {
				res.setResultNote("订单ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("type"))) {
				res.setResultNote("TYPE类型不能为空！");
				return res;
			}
			if ("0".equals(req.getString("type"))) {// 云店订单
				ProductOrder o = productOrderService.get(req.getString("orderId"));
				if (o == null) {
					res.setResultNote("该订单不存在！");
					return res;
				}
				if(!"2".equals(o.getState())){
					res.setResultNote("该订单不是待收货状态！");
					return res;
				}
				o.setState("3");
				o.setFinishDate(new Date());
				productOrderService.finish(o);
				//productOrderService.save(o);

				// 处理代理申请
				/*if ("1".equals(o.getProxyType())) {
					// 判断所有订单
					ProductOrder productOrder = new ProductOrder();
					productOrder.setTotalId(o.getTotalId());
					List<ProductOrder> list = productOrderService.findList(productOrder);
					boolean flag = false;
					for (ProductOrder order : list) {
						if (!"3".equals(order.getState()) && !"4".equals(order.getState())) {
							flag = true;
						}
					}
					if (!flag) {
						// 调用三方接口
						List<WohuiEntity> entityList = Lists.newArrayList();
						entityList.add(new WohuiEntity("POrderNO", o.getTotalId()));
						JSONObject jsonObject = WohuiUtils.send(WohuiUtils.MSMSureSign, entityList);
						if (!"0000".equals(jsonObject.getString("respCode"))) {
							logger.error("三方会员系统代理确认收货失败：" + jsonObject.getString("respMsg"));
						}
					}
				}*/
			} else if ("1".equals(req.getString("type"))) {// 拼团订单
				GroupOrder o = groupOrderService.get(req.getString("orderId"));
				if (o == null) {
					res.setResultNote("该订单不存在！");
					return res;
				}
				if(!"2".equals(o.getState())){
					res.setResultNote("该订单不是待收货状态！");
					return res;
				}
//				if(!req.getString("th_code").equals(o.getThCode())){
//					res.setResultNote("提货码错误请重试！");
//					return res;
//				}
				o.setState("3");
				o.setFinishDate(new Date());
				groupOrderService.finish(o);
				//groupOrderService.save(o);

				// 处理代理申请
				/*if ("1".equals(o.getProxyType())) {
					// 调用三方接口
					List<WohuiEntity> entityList = Lists.newArrayList();
					entityList.add(new WohuiEntity("POrderNO", o.getId()));
					JSONObject jsonObject = WohuiUtils.send(WohuiUtils.MSMSureSign, entityList);
					if (!"0000".equals(jsonObject.getString("respCode"))) {
						logger.error("三方会员系统代理确认收货失败：" + jsonObject.getString("respMsg"));
					}
				}*/
			}
			res.setResult("0");
			res.setResultNote("确认成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 去评价
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/evaluateOrder")
	@ResponseBody
	public ResJson evaluateOrder(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("评价失败！");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("orderId"))) {
				res.setResultNote("订单ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("shopScore"))) {
				res.setResultNote("请选择商家评分！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("evaluateList"))) {
				res.setResultNote("请评价商品！");
				return res;
			}
			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}
			if ("0".equals(req.getString("type"))) {// 云店订单
				ProductOrder o = productOrderService.get(req.getString("orderId"));
				if (o == null) {
					res.setResultNote("该订单不存在！");
					return res;
				}
				// 向商家评价表中插入一条数据
				StoreScore ss = new StoreScore();
				ss.setIsNewRecord(true);
				ss.setId(IdGen.uuid());
				ss.setMember(member);
				ss.setStore(o.getStore());
				ss.setScore(req.getIntValue("shopScore"));
				ss.setOrderId(o.getId());
				ss.setCreateDate(new Date());
				storeScoreService.save(ss);
				// 向商品评价表中插入一条数据
				JSONArray evaluateList = req.getJSONArray("evaluateList");
				if (evaluateList != null && !evaluateList.isEmpty()) {
					for (int i = 0; i < evaluateList.size(); i++) {
						JSONObject object = evaluateList.getJSONObject(i);
						// 根据订单项ID查询信息
						OrderItem oi = orderItemMapper.get(object.getString("itemId"));
						if (oi != null) {
							Comment c1 = new Comment();
							c1.setMember(member);
							c1.setOrderId(o.getId());
							c1.setStore(o.getStore());
							c1.setProduct(new Product(oi.getProductId()));
							c1.setSkuId(oi.getSkuId());
							c1.setProductTitle(oi.getProductTitle());
							c1.setProductIcon(oi.getProductIcon());
							c1.setSkuTitle(oi.getSkuName());
							c1.setPrice(oi.getPrice());
							c1.setQty(oi.getQty());
							c1.setScore(object.getIntValue("score"));
							c1.setContent(object.getString("content"));
							c1.setImages("");
							JSONArray images = object.getJSONArray("images");
							if (images != null && !images.isEmpty()) {
								c1.setImages(StringUtils.join(images, "|"));
							}
							c1.setState("0");
							commentService.save(c1);
						}
					}
				}
				/*List<Comment> commentList = JSONObject.parseArray(req.getString("evaluateList"), Comment.class);
				if (commentList != null && commentList.size() > 0) {
					for (Comment c : commentList) {
						// 根据订单项ID查询信息
						OrderItem oi = orderItemMapper.get(c.getItemId());
						if (oi != null) {
							Comment c1 = new Comment();
							c1.setIsNewRecord(true);
							c1.setId(IdGen.uuid());
							c1.setMember(member);
							c1.setOrderId(o.getId());
							c1.setStore(o.getStore());
							c1.setProduct(new Product(c.getProductId()));
							c1.setSkuId(oi.getSkuId());
							c1.setProductTitle(oi.getProductTitle());
							c1.setProductIcon(oi.getProductIcon());
							c1.setSkuTitle(oi.getSkuName());
							c1.setPrice(oi.getPrice());
							c1.setQty(oi.getQty());
							c1.setScore(c.getScore());
							c1.setContent(c.getContent());
							c1.setImages(c.getImages());
							c1.setCreateDate(new Date());
							c1.setState("0");
							commentService.save(c1);
						}
					}
				}*/
				o.setState("4");
				o.setCompleteDate(new Date());
				productOrderService.save(o);
			} else if ("1".equals(req.getString("type"))) {// 拼团订单
				// 云店订单
				GroupOrder o = groupOrderService.get(req.getString("orderId"));
				if (o == null) {
					res.setResultNote("该订单不存在！");
					return res;
				}
				// 向商家评价表中插入一条数据
				StoreScore ss = new StoreScore();
				ss.setIsNewRecord(true);
				ss.setId(IdGen.uuid());
				ss.setMember(member);
				ss.setStore(o.getStore());
				ss.setScore(req.getIntValue("shopScore"));
				ss.setOrderId(o.getId());
				ss.setCreateDate(new Date());
				storeScoreService.save(ss);
				// 向商品评价表中插入一条数据
				JSONArray evaluateList = req.getJSONArray("evaluateList");
				if (evaluateList != null && !evaluateList.isEmpty()) {
					for (int i = 0; i < evaluateList.size(); i++) {
						JSONObject object = evaluateList.getJSONObject(i);
						Comment c1 = new Comment();
						c1.setMember(member);
						c1.setOrderId(o.getId());
						c1.setStore(o.getStore());
						c1.setProduct(o.getProduct());
						c1.setSkuId(o.getSkuId());
						c1.setProductTitle(o.getProductTitle());
						c1.setProductIcon(o.getProductIcon());
						c1.setSkuTitle(o.getSkuName());
						c1.setPrice(o.getPrice());
						c1.setQty(o.getQty());
						c1.setScore(object.getIntValue("score"));
						c1.setContent(object.getString("content"));
						c1.setImages("");
						JSONArray images = object.getJSONArray("images");
						if (images != null && !images.isEmpty()) {
							c1.setImages(StringUtils.join(images, "|"));
						}
						c1.setState("0");
						commentService.save(c1);
					}
				}
				o.setState("4");
				groupOrderService.save(o);
			}
			res.setResult("0");
			res.setResultNote("评价成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 版本更新
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/getversion")
	@ResponseBody
	public ResJson getversion(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		try {
			List<Upgrade> uList = upgradeService.findList(new Upgrade());
			if (uList != null && uList.size() > 0) {
				res.put("minnumber", uList.get(0).getMinnumber());
				res.put("number", uList.get(0).getNumber());
				res.put("version", uList.get(0).getVersion());
				res.put("url", uList.get(0).getUrl());
				res.put("content", uList.get(0).getContent());
				res.put("type", uList.get(0).getType());
			}
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 申请全国总店选店铺序号列表
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/findStoreList")
	@ResponseBody
	public ResJson findStoreList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		List<Map<String, Object>> dataList = Lists.newArrayList();
		try {
			Store store = new Store();
			if (StringUtils.isNotBlank(req.getString("keyword"))) {
				store.setStoreCode(req.getString("keyword"));
			}
			store.setState("0");
			store.setAuditState("2");
			Page<Store> page = storeService.findPage(new Page<Store>(req.getPageNo(), req.getPageSize()), store);
			for (Store n : page.getList()) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("storeId", n.getId());
				map.put("storeCode", n.getStoreCode());
				map.put("storeName", n.getTitle());
				dataList.add(map);
			}
			res.setTotalPage(page.getTotalPage());
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 根据厂家ID查询厂家商品列表（申请全国总店选择用）
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/findProductListStoreId")
	@ResponseBody
	public ResJson findProductListStoreId(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		List<Map<String, Object>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getString("storeId"))) {
				res.setResultNote("厂家ID不能为空！");
				return res;
			}
			Product product = new Product();
			if (StringUtils.isNotBlank(req.getString("keyword"))) {
				product.setCode(req.getString("keyword"));
			}
			product.setStore(new Store(req.getString("storeId")));
			product.setState("0");
			product.setAuditState("1");
			Page<Product> page = productService.findPage(new Page<Product>(req.getPageNo(), req.getPageSize()),
					product);
			for (Product n : page.getList()) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("productId", n.getId());
				map.put("productCode", n.getCode());
				map.put("productName", n.getTitle());
				dataList.add(map);
			}
			res.setTotalPage(page.getTotalPage());
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}


	/**
	 * 云店首页信息
	 * @param req
	 * @return
	 */
	@PostMapping("/cloudShopIndex")
	@ResponseBody
	public ResJson indexInfo(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		try {
			// 轮播图列表
			List<Map<String, Object>> bannerList = Lists.newArrayList();
			Banner banner = new Banner();
			banner.setType("1");
			List<Banner> list = bannerService.findList(banner);
			for (Banner b : list) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("image", getRealImage(b.getImage()));
				map.put("category", b.getCategory());
				map.put("url", b.getUrl());
				map.put("productId", b.getProduct() != null ? b.getProduct().getId() : "");
				map.put("storeId", b.getStore() != null ? b.getStore().getId() : "");
				map.put("thirdLink", StringUtils.isNotBlank(b.getThirdLink()) ? b.getThirdLink() : "");
				map.put("productCategoryId", b.getProductCategory() != null ? b.getProductCategory().getId() : "");
				map.put("productCategoryName", b.getProductCategory() != null ? b.getProductCategory().getName() : "");
				bannerList.add(map);
			}
			res.put("bannerList", bannerList);
			// 一级分类列表
			List<Map<String, Object>> categoryList = Lists.newArrayList();
			ProductCategory productCategory = new ProductCategory();
			productCategory.setType("1");
			productCategory.setState("0");
			List<ProductCategory> cList = productCategoryService.findList(productCategory);
			if (cList != null && cList.size() > 0) {
				for (ProductCategory c : cList) {
					Map<String, Object> map = Maps.newHashMap();
					map.put("id", c.getId());
					map.put("name", c.getName());
					categoryList.add(map);
				}
			}
			res.put("categoryList", categoryList);
			// 类别列表
			List<Map<String, Object>> typeList = Lists.newArrayList();
			List<Tags> tList = tagsService.findList(new Tags());
			if (tList != null && tList.size() > 0) {
				for (Tags t : tList) {
					Map<String, Object> map = Maps.newHashMap();
					map.put("title", t.getTitle());
					map.put("type", t.getType());
					map.put("icon", getRealImage(t.getIcon()));
					typeList.add(map);
				}
			}
			res.put("typeList", typeList);
			// 云店特色列表
			List<Map<String, String>> specialList = Lists.newArrayList();
			List<SpecialProduct> sList = specialProductService.findList(new SpecialProduct());
			if (sList != null && sList.size() > 0) {
				for (SpecialProduct s : sList) {
					Map<String, String> map = Maps.newHashMap();
					map.put("type", s.getType());
					map.put("id", s.getProduct().getId());
					map.put("name", s.getProduct().getTitle());
					map.put("image", getRealImage(s.getProduct().getIcon()));
					map.put("price", s.getProduct().getPrice());
					map.put("originalPrice", s.getProduct().getOldPrice());
					map.put("integral", s.getProduct().getPoint());
					map.put("couponMoney", s.getProduct().getDiscount());
					specialList.add(map);
				}
			}
			res.put("specialList", specialList);
			// 商品列表
			List<Map<String, Object>> dataList = Lists.newArrayList();
			Product product = new Product();
			//product.setDataScope(" AND category.hot = '1' ");
			product.setAuditState("1");
			product.setState("0");
			product.setIsshow("0");
			product.setIsTuijian("1");
			Page<Product> page2 = new Page<Product>(req.getPageNo(), req.getPageSize());
			page2.setOrderBy(" a.sales DESC ");
			//product.setDataScope(" AND a.sales > 200 ");
			Page<Product> page = productService.findPage(page2, product);
			for (Product n : page.getList()) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("productId", n.getId());
				map.put("coverImage", getRealImage(n.getIcon()));
				map.put("productName", n.getTitle());
				map.put("price", n.getPrice());
				map.put("originalPrice", n.getOldPrice());
				map.put("couponMoney", n.getDiscount());
				map.put("integral", n.getPoint());
				map.put("salesVolume", n.getSales());
				dataList.add(map);
			}
			res.setTotalPage(page.getTotalPage());
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
    /**
     * 云店首页分类列表
     * @return
     */
    @PostMapping("/yundianCategory")
    @ResponseBody
    public ResJson yundianCategory() {
        ResJson res = new ResJson();
        res.setResultNote("查询失败");
        try {

			// 一级分类列表
			List<Map<String, Object>> categoryList = Lists.newArrayList();
			ProductCategory productCategory = new ProductCategory();
			productCategory.setType("1");
			productCategory.setState("0");
			List<ProductCategory> cList = productCategoryService.findList(productCategory);
			if (cList != null && cList.size() > 0) {
				for (ProductCategory c : cList) {
					Map<String, Object> map = Maps.newHashMap();
					map.put("id", c.getId());
					map.put("name", c.getName());
					map.put("icon", c.getIcon());
					categoryList.add(map);
				}
			}
            res.setDataList(categoryList);
            res.setResult("0");
            res.setResultNote("查询成功");
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return res;
    }

	/**
	 * 拼团商品列表
	 * @param req
	 * @return
	 */
	@PostMapping("/groupProductList")
	@ResponseBody
	public ResJson groupProductList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		try {
			// 商品列表
			List<Map<String, Object>> dataList = Lists.newArrayList();
			Product product = new Product();
			product.setIsGroup("1");
			product.setAuditState("1");
			product.setState("0");
			Page<Product> page = productService.findPage(new Page<Product>(req.getPageNo(), req.getPageSize()),
					product);
			for (Product n : page.getList()) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("productId", n.getId());
				map.put("coverImage", getRealImage(n.getIcon()));
				map.put("productName", n.getTitle());
				map.put("price", n.getPrice());
				map.put("originalPrice", n.getOldPrice());
				map.put("integral", n.getPoint());
				map.put("grouprice", n.getGroupPrice());
				map.put("PtRenNum", n.getPtRenNum());
				dataList.add(map);
			}
			res.setTotalPage(page.getTotalPage());
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 爆品/新品商品列表(现在是砍一刀专区)
	 * @param req
	 * @return
	 */
	@PostMapping("/explosiveOrNewsList")
	@ResponseBody
	public ResJson explosiveOrNewsList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		try {
			if (StringUtils.isBlank(req.getString("type"))) {
				res.setResultNote("TYPE类型不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("sortType"))) {
				res.setResultNote("排序类型不能为空！");
				return res;
			}
			// 商品列表
			List<Map<String, Object>> dataList = Lists.newArrayList();
			Product product = new Product();
			if ("0".equals(req.getString("type"))) {// 爆品
				product.setIsHot("1");
			} else if ("1".equals(req.getString("type"))) {
				product.setIsNew("1");
			}else if ("3".equals(req.getString("type"))) {// 惠省专区
				product.setIsbd("2");
			}
//			else if ("4".equals(req.getString("type"))){// 复购专区
//				if (StringUtils.isBlank(req.getString("RebuyType"))) {
//					res.setResultNote("复购类型不能为空！");
//					return res;
//				}
//				if("2".equals(req.getString("RebuyType"))){
//					String dataScope = " AND a.id = '4117373ca116433ba6b016dd5aa4804a' OR a.id = 'deaf6a50463d4d6e9e2c70b0b645e91d'";
//					product.setDataScope(dataScope);
//				}else if("0".equals(req.getString("RebuyType"))){//399复购
//					String dataScope = " AND a.id = '4117373ca116433ba6b016dd5aa4804a'";
//					product.setDataScope(dataScope);
//				}else if("1".equals(req.getString("RebuyType"))){//299代理自用
//					String dataScope = " AND a.id = 'deaf6a50463d4d6e9e2c70b0b645e91d'";
//					product.setDataScope(dataScope);
//				}else if("3".equals(req.getString("RebuyType"))){//数据为空
//					product.setIsshow("5");
//				}
//			}
			else if ("5".equals(req.getString("type"))){// 爆品购物券兑换专区
				product.setIsbd("3");
			}else if ("6".equals(req.getString("type"))){// 我惠健康专区
				product.setIsbd("4");
				product.setIsshow("0");
			}else if ("7".equals(req.getString("type"))){// 血德平复购专区
				product.setIsbd("5");
			}else if ("8".equals(req.getString("type"))){// C2F专区
				product.setIsbd("6");
			}else if ("4".equals(req.getString("type"))){// 代理进货
				if (StringUtils.isBlank(req.getString("RebuyType"))) {
					res.setResultNote("代理进货类型不能为空！");
					return res;
				}
				String type10 ="0";
				String type20 ="0";
				String type30 ="0";
				String type31 ="0";
				if (StringUtils.isNotBlank(req.getString("RebuyType"))) {
					String[] BHRebuy = req.getString("RebuyType").split(",");
					List<String> rolesList = Arrays.asList(BHRebuy);
					if (rolesList.contains("10")) {
						type10 = "1";
					}
					if (rolesList.contains("20")) {
						type20 = "1";
					}
					if (rolesList.contains("30")) {
						type30 = "1";
					}
					if (rolesList.contains("31")) {
						type31 = "1";
					}
				}
				//ecfadb9250204850b11ead9aa398df9d 买一送一鸣鹤同舟酸康宝大盒装体验600克/盒代理进货 ca3dc0eb8ab04c59b98f6ff76ca9001b 买一送一鸣鹤同舟华蒜豆900克/盒固体饮料瓶装袋装代理进货
				//09978529550649b18cacee85ad7500ff 	买一送一血德平葛参肽压片糖果一盒40片植物提取代理进货 15a62c70a1d74e34a059e74dde3336d8 买一送一鬼谷回春堂压片糖果一盒30粒葛根代理进货
				String dataScope="";
				if("1".equals(type10)){
					dataScope += " AND a.id = '15a62c70a1d74e34a059e74dde3336d8'";
					if("1".equals(type20)){
						dataScope += " OR a.id = '09978529550649b18cacee85ad7500ff'";
					}
					if("1".equals(type30)){
						dataScope += " OR a.id = 'ecfadb9250204850b11ead9aa398df9d'";
					}
					if("1".equals(type31)){
						dataScope += " OR a.id = 'ca3dc0eb8ab04c59b98f6ff76ca9001b'";
					}
					product.setDataScope(dataScope);
				}else if("1".equals(type20)){
						dataScope += " AND a.id = '09978529550649b18cacee85ad7500ff'";
						if("1".equals(type30)){
							dataScope += " OR a.id = 'ecfadb9250204850b11ead9aa398df9d'";
						}
						if("1".equals(type31)){
							dataScope += " OR a.id = 'ca3dc0eb8ab04c59b98f6ff76ca9001b'";
						}
					product.setDataScope(dataScope);
				}else if("1".equals(type30)){
					dataScope += " AND a.id = 'ecfadb9250204850b11ead9aa398df9d'";
					if("1".equals(type31)){
						dataScope += " OR a.id = 'ca3dc0eb8ab04c59b98f6ff76ca9001b'";
					}
					product.setDataScope(dataScope);
				}else if("1".equals(type31)){
					dataScope += " AND a.id = 'ca3dc0eb8ab04c59b98f6ff76ca9001b'";
					product.setDataScope(dataScope);
				}
			}
			product.setAuditState("1");
			product.setState("0");
			Page<Product> page = new Page<Product>(req.getPageNo(), req.getPageSize());

			if ("1".equals(req.getString("sortType"))) {// 销量升序
				page.setOrderBy("a.sales ASC");
			} else if ("2".equals(req.getString("sortType"))) {// 销量降序
				page.setOrderBy("a.sales DESC");
			} else if ("3".equals(req.getString("sortType"))) {// 价格升序
				page.setOrderBy("a.price ASC");
			} else if ("4".equals(req.getString("sortType"))) {// 价格降序
				page.setOrderBy("a.price DESC");
			} else if ("5".equals(req.getString("sortType"))) {// 铜板升序
				page.setOrderBy("a.point ASC");
			} else if ("6".equals(req.getString("sortType"))) {// 铜板降序
				page.setOrderBy("a.point DESC");
			}
			page = productService.findPage(page, product);
			for (Product n : page.getList()) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("productId", n.getId());
				map.put("coverImage", getRealImage(n.getIcon()));
				map.put("productName", n.getTitle());
				map.put("price", n.getPrice());
				map.put("originalPrice", n.getOldPrice());
				map.put("couponMoney", n.getDiscount());
				map.put("integral", n.getPoint());
				map.put("salesVolume", n.getSales());
				map.put("isbd", n.getIsbd());
				map.put("ishot", n.getIsHot());
				map.put("diff", n.getDiffprice());
				map.put("subsidyprice", n.getSubsidyprice());
				map.put("openprice", n.getOpenprice());
				map.put("type", req.getString("type"));
				dataList.add(map);
			}
			res.setTotalPage(page.getTotalPage());
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 活动接口
	 * @param req
	 * @return
	 */
	@PostMapping("/getHdongUrl")
	@ResponseBody
	public ResJson getHdongUrl(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.put("status","2");
		try {
			Map<String, String> params = Maps.newHashMap();
			//判断是否登陆
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("请先登录");
				return res;
			}
			//判断参数是否为空
			if (StringUtils.isBlank(req.getString("promotion_scene_id"))) {
				res.setResultNote("官方活动id不能为空！");
				return res;
			}
			//判断是否绑定推广渠道活得relation_id
			Member member = memberService.get(req.getString("uid"));
			if(StringUtils.isNotBlank(member.getRelationId())){
				params.put("relation_id",member.getRelationId());
			}else{
				res.setResult("0");
				res.put("status","1");
				res.setResultNote("您没有绑定推广渠道id！");
				return res;
			}
			params.put("sid", MiaoyouquanUtils.sid);// 对应的淘客账号授权ID
			params.put("union_id", "");// 生成union_id
			params.put("platform", "2");// 默认无线
			params.put("adzone_id","109652350334");// 生成adzone_id
			params.put("site_id","910450299");// 生成site_id
			params.put("promotion_scene_id",req.getString("promotion_scene_id"));// 生成promotion_scene_id
			JSONObject jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.open_activitylink_get, params);
			logger.debug("折淘客返回数据：" + jsonObject.toString());
//			jsonObject=jsonObject.getJSONObject("tbk_sc_activitylink_toolget_response");
			jsonObject=jsonObject.getJSONObject("tbk_sc_activity_info_get_response");
//			if (!"200".equals(jsonObject.getString("result_code"))) {
//				res.setResultNote("数据异常！");
//				return res;
//			}

			JSONObject jsonArray2 = jsonObject.getJSONObject("data");
			res.put("hDongUrl", jsonObject.getJSONObject("data").getString("click_url"));//返回链接
			res.put("shorthDongUrl", jsonObject.getJSONObject("data").getString("short_click_url"));//返回链接
//			Map<String, String> params2 = Maps.newHashMap();
//			params2.put("sid", MiaoyouquanUtils.sid);// 对应的淘客账号授权ID
//			params2.put("content", jsonObject.getJSONObject("data").getString("click_url"));// 生成union_id
//
//			JSONObject jsonObject2 = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.open_shorturl_taobao_get, params2);
//			logger.debug("折淘客返回数据：" + jsonObject2.toString());
//			res.put("ChainDongUrl", jsonObject2.getString("shorturl"));//返回链接
            res.setResult("0");
            res.put("status","0");
            res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
			res.setResult(e.getMessage());
		}
		return res;
	}
	/**
	 * 查询用户分享任务进度
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/ForOrdertasklist")
	@ResponseBody
	public ResJson ForOrdertasklist(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		List<Map<String, Object>> dataList = Lists.newArrayList();

		List<String> clickguidList = Lists.newArrayList();
		List<String> clickiconList = Lists.newArrayList();
		List<String> clicknameList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getUid())) {
				res.setResultNote("请先登录");
				return res;
			}
            if (StringUtils.isBlank(req.getString("productId"))) {
                res.setResultNote("商品id不能为空");
                return res;
            }
			Map<String, Object> map =  Maps.newHashMap();
			List<Map<String,Object>> list = ordertaskService.executeSelectSql("SELECT uid,num,orderno,id,state,click_guid,click_icon,click_name,create_date,expire_date FROM t_order_task WHERE uid='"+req.getString("uid")+"' and  productid='"+req.getString("productId")+"' and state < 2 AND expire_date > NOW() ORDER BY create_date DESC");
			if (list == null || list.isEmpty()) {
				res.setResult("0");
				res.setResultNote("还未开始任务");
				return  res;
			}
			if(list.get(0).get("click_guid") !=null && !list.get(0).get("click_guid").toString().isEmpty() ){
				String clickguid[] =list.get(0).get("click_guid").toString().split(",");
				clickguidList = Arrays.asList(clickguid);
			}
			if( list.get(0).get("click_icon") !=null && !list.get(0).get("click_icon").toString().isEmpty() ){
				String click_icon[]=list.get(0).get("click_icon").toString().split(",");
				clickiconList = Arrays.asList(click_icon);
			}
			if(list.get(0).get("click_name") !=null && !list.get(0).get("click_name").toString().isEmpty() ){
				String clickname[]  =list.get(0).get("click_name").toString().split(",");
				clicknameList = Arrays.asList(clickname);
			}
			map.put("clickguidList", clickguidList);
			map.put("clickiconList", clickiconList);
			map.put("clicknameList", clicknameList);
			map.put("num", list.get(0).get("num").toString());
			map.put("createdate", list.get(0).get("create_date") != null ? DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(list.get(0).get("create_date")) : "");
			map.put("expiredate", list.get(0).get("expire_date") != null ? DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(list.get(0).get("expire_date")) : "");
			map.put("id", list.get(0).get("id"));
			map.put("state", list.get(0).get("state"));
			dataList.add(map);
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 创建任务进度
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/ForOrdertaskCreate")
	@ResponseBody
	public ResJson ForOrdertaskCreate(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getUid())) {
				res.setResultNote("请先登录");
				return res;
			}
			if (StringUtils.isBlank(req.getString("productId"))) {
				res.setResultNote("商品id不能为空");
				return res;
			}
			Map<String, Object> map =  Maps.newHashMap();

			List<Map<String,Object>> list = ordertaskService.executeSelectSql("SELECT uid,num,orderno,id,state,click_guid,click_icon,click_name,create_date,expire_date FROM t_order_task WHERE uid='"+req.getString("uid")+"' and  productid='"+req.getString("productId")+"' and state <2 AND expire_date > NOW() ORDER BY create_date DESC");
			if (list == null || list.isEmpty()) {
				Ordertask ordertask = new Ordertask();
				ordertask.setCreatedate(new Date());
				ordertask.setExpiredate(DateUtils.addDays(new Date(), 1));
				ordertask.setNum("0");
				ordertask.setProductid(req.getString("productId"));
				ordertask.setMember(new Member(req.getUid()));
				ordertask.setState("0");
				ordertaskService.insert(ordertask);
				res.put("id", ordertask.getId());
				res.setResult("0");
				res.setResultNote("获取成功");
			}
			res.put("id", list.get(0).get("id"));
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 用户分享wancheng任务
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/ForOrdertaskClick")
	@ResponseBody
	public ResJson ForOrdertaskClick(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		List<Map<String, String>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getUid())) {
				res.setResultNote("请先登录");
				return res;
			}
			Member member = memberService.get(req.getUid());
			if (member == null) {
				res.setResultNote("用户不存在");
				return res;
			}
			if (StringUtils.isBlank(req.getString("name"))) {
				res.setResultNote("用户昵称不能为空");
				return res;
			}
			if (StringUtils.isBlank(req.getString("icon"))) {
				res.setResultNote("头像地址不能为空");
				return res;
			}
			if (StringUtils.isBlank(req.getString("id"))) {
				res.setResultNote("分享任务ID不能为空");
				return res;
			}
			Ordertask ordertask = ordertaskService.get(req.getString("id"));
			if(ordertask !=null && "0".equals(ordertask.getState()) ){
				if(ordertask.getExpiredate().compareTo(new Date()) < 0){//超时超时小于现在时间
					res.setResultNote("该分享任务已失效");
					return  res;
				}
				ordertask.setNum(new BigDecimal(ordertask.getNum()).add(new BigDecimal(1)).toString());
				if(ordertask.getClickguid()!= null && !ordertask.getClickguid().isEmpty()){
					String[] roles =ordertask.getClickguid().split(",");
					List<String> rolesList = Arrays.asList(roles);
					if (rolesList.contains(req.getUid())) {
						res.setResultNote("你已经助力过该用户了");
						return res;
					}
					ordertask.setClickguid(ordertask.getClickguid()+","+req.getUid());
				}else {
					ordertask.setClickguid(req.getUid());
				}
				if(ordertask.getClickicon()!= null && !ordertask.getClickicon().isEmpty()){
					ordertask.setClickicon(ordertask.getClickicon()+","+req.getString("icon"));
				}else {
					ordertask.setClickicon(req.getString("icon"));
				}
				if(ordertask.getClickname()!= null && !ordertask.getClickname().isEmpty()){
					ordertask.setClickname(ordertask.getClickname()+","+req.getString("name"));
				}else {
					ordertask.setClickname(req.getString("name"));
				}
				ordertask.setUpdateDate(new Date());
				if("5".equals(ordertask.getNum()) && "0".equals(ordertask.getState())){
					ordertask.setState("1");
				}
				ordertaskMapper.update(ordertask);
				if(new BigDecimal(ordertask.getNum()).compareTo(new BigDecimal(5)) > -1){
					res.setResultNote("任务完成,助力成功！");
					return res;
				}
			}else{
				res.setResult("1");
				res.setResultNote("任务助力失败！");
				return res;
			}
			res.setResult("0");
			res.setResultNote("任务助力成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 用户分享wancheng任务
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/ForOrdertaskinfo")
	@ResponseBody
	public ResJson ForOrdertaskinfo(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("id"))) {
				res.setResultNote("分享任务ID不能为空");
				return res;
			}
			Ordertask ordertask = ordertaskService.get(req.getString("id"));
			if(ordertask ==null){
				res.setResultNote("任务获取失败");
				return  res;
			}

			if(ordertask.getExpiredate().compareTo(new Date()) < 0){//超时小于现在时间
				res.setResultNote("该分享任务已失效");
				return  res;
			}
			res.put("name",ordertask.getMember().getNickname());
			res.put("icon",ordertask.getMember().getIcon());
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 物流接口
	 * @param req
	 * @return
	 */
	@PostMapping("/getExpressList")
	@ResponseBody
	public ResJson getExpressList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		try {
			Map<String, String> params = Maps.newHashMap();
			//判断快递公司
			if (StringUtils.isBlank(req.getString("express"))) {
				res.setResultNote("快递公司不能为空");
				return res;
			}
			//判断订单号
			if (StringUtils.isBlank(req.getString("expresssn"))) {
				res.setResultNote("订单号不能为空！");
				return res;
			}
			new KuaidiEntity(req.getString("expresssn"),req.getString("express"));//快递公司
			String kuaiDi=ToolsUtil.send();//获取快递信息
			JSONObject jsonObject = JSONObject.parseObject(kuaiDi);//转换成json对象
			if(!"0000".equals(jsonObject.getString("code"))){
				res.setResultNote(jsonObject.getString("data"));
				return res;
			}
			res.put("data",jsonObject.getJSONArray("data"));
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
			res.setResult(e.getMessage());
		}
		return res;
	}
	/**
	 * 根据一级分类查询商品列表
	 * @param req
	 * @return
	 */
	@PostMapping("/findProductByYjCategory")
	@ResponseBody
	public ResJson findProductByYjCategory(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		try {
			if (StringUtils.isBlank(req.getString("categoryId"))) {
				res.setResultNote("分类ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("sortType"))) {
//				res.setResultNote("排序类型不能为空！");
//				return res;
				req.put("sortType","0");
			}
			// 商品列表
			// 二级分类列表
			List<Map<String, Object>> categoryList = Lists.newArrayList();
			ProductCategory productCategory = new ProductCategory();
			productCategory.setParent(new ProductCategory(req.getString("categoryId")));
			productCategory.setType("2");
			productCategory.setState("0");
			List<ProductCategory> cList = productCategoryService.findList(productCategory);
			if (cList != null && cList.size() > 0) {
				for (ProductCategory c : cList) {
					Map<String, Object> map = Maps.newHashMap();
					map.put("id", c.getId());
					map.put("icon", getRealImage(c.getIcon()));
					map.put("name", c.getName());
					categoryList.add(map);
				}
			}
			res.put("categoryList", categoryList);
			// 商品列表
			List<Map<String, Object>> dataList = Lists.newArrayList();
			Product product = new Product();
			product.setDataScope(" AND a.category_id IN (SELECT b.id FROM t_product_category b WHERE b.parent_id='"
					+ req.getString("categoryId") + "')");
			product.setAuditState("1");
			product.setState("0");
			product.setIsshow("0");
			Page<Product> page2 = new Page<Product>(req.getPageNo(), req.getPageSize());
			if ("1".equals(req.getString("sortType"))) {// 销量升序
				page2.setOrderBy("a.sales ASC");
			} else if ("2".equals(req.getString("sortType"))) {// 销量降序
				page2.setOrderBy("a.sales DESC");
			} else if ("3".equals(req.getString("sortType"))) {// 价格升序
				page2.setOrderBy("a.price ASC");
			} else if ("4".equals(req.getString("sortType"))) {// 价格降序
				page2.setOrderBy("a.price DESC");
			} else if ("5".equals(req.getString("sortType"))) {// 铜板升序
				page2.setOrderBy("a.point ASC");
			} else if ("6".equals(req.getString("sortType"))) {// 铜板降序
				page2.setOrderBy("a.point DESC");
			}
//			page2.setOrderBy(" a.sales DESC ");
			Page<Product> page = productService.findPage(page2, product);
			for (Product n : page.getList()) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("productId", n.getId());
				map.put("coverImage", getRealImage(n.getIcon()));
				map.put("productName", n.getTitle());
				map.put("price", n.getPrice());
				map.put("originalPrice", n.getOldPrice());
				map.put("couponMoney", n.getDiscount());
				map.put("integral", n.getPoint());
				map.put("salesVolume", n.getSales());
                map.put("ishot", n.getIsHot());
                map.put("diff", n.getDiffprice());
                map.put("grouprice", n.getGroupPrice());
                map.put("isbd", n.getIsbd());
				dataList.add(map);
			}
			res.setTotalPage(page.getTotalPage());
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 根据二级分类查询商品列表
	 * @param req
	 * @return
	 */
	@PostMapping("/findProductByEjCategory")
	@ResponseBody
	public ResJson findProductByEjCategory(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		try {
			if (StringUtils.isBlank(req.getString("categoryId"))) {
				res.setResultNote("分类ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("sortType"))) {
				res.setResultNote("排序类型不能为空！");
				return res;
			}
			// 商品列表
			List<Map<String, Object>> dataList = Lists.newArrayList();
			Product product = new Product();
			product.setCategory(new ProductCategory(req.getString("categoryId")));
			product.setAuditState("1");
			product.setState("0");
			product.setIsshow("0");

			Page<Product> page = new Page<Product>(req.getPageNo(), req.getPageSize());
			if ("1".equals(req.getString("sortType"))) {// 销量升序
				page.setOrderBy("a.sales ASC");
			} else if ("2".equals(req.getString("sortType"))) {// 销量降序
				page.setOrderBy("a.sales DESC");
			} else if ("3".equals(req.getString("sortType"))) {// 价格升序
				page.setOrderBy("a.price ASC");
			} else if ("4".equals(req.getString("sortType"))) {// 价格降序
				page.setOrderBy("a.price DESC");
			} else if ("5".equals(req.getString("sortType"))) {// 铜板升序
				page.setOrderBy("a.point ASC");
			} else if ("6".equals(req.getString("sortType"))) {// 铜板降序
				page.setOrderBy("a.point DESC");
			}
			page = productService.findPage(page, product);

			for (Product n : page.getList()) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("productId", n.getId());
				map.put("coverImage", getRealImage(n.getIcon()));
				map.put("productName", n.getTitle());
				map.put("price", n.getPrice());
				map.put("originalPrice", n.getOldPrice());
				map.put("couponMoney", n.getDiscount());
				map.put("integral", n.getPoint());
				map.put("salesVolume", n.getSales());
                map.put("ishot", n.getIsHot());
                map.put("diff", n.getDiffprice());
                map.put("grouprice", n.getGroupPrice());
                map.put("isbd", n.getIsbd());
				dataList.add(map);
			}
			res.setTotalPage(page.getTotalPage());
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 扶贫专区省份列表
	 * @param req
	 * @return
	 */
	@PostMapping("/provinceList")
	@ResponseBody
	public ResJson provinceList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		try {
			List<Map<String, Object>> dataList = Lists.newArrayList();
			Area area = new Area();
			area.setType("1");
			List<Area> aList = areaService.findList(area);
			if (aList != null && aList.size() > 0) {
				for (Area a : aList) {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("id", a.getId());// 省份ID
					map.put("name", a.getName());// 省份名称
					dataList.add(map);
				}
			}
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 扶贫专区根据省份ID查询市县列表
	 * @param req
	 * @return
	 */
	@PostMapping("/cityAndDistrictList")
	@ResponseBody
	public ResJson cityAndDistrictList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		try {
			if (StringUtils.isBlank(req.getString("provinceId"))) {
				res.setResultNote("省份ID不能为空！");
				return res;
			}
			List<Map<String, Object>> dataList = Lists.newArrayList();
			Area area = new Area();
			area.setParent(new Area(req.getString("provinceId")));
			area.setType("2");
			List<Area> aList = areaService.findList(area);
			if (aList != null && aList.size() > 0) {
				for (Area a : aList) {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("id", a.getId());// 城市ID
					map.put("name", a.getName());// 城市名称
					// 根据城市ID查询该分类下的区县列表
					List<Map<String, Object>> areaList = new ArrayList<Map<String, Object>>();
					Area area1 = new Area();
					area1.setParent(new Area(a.getId()));
					area1.setType("3");
					List<Area> aList1 = areaService.findList(area1);
					if (aList1 != null && aList1.size() > 0) {
						for (Area a1 : aList1) {
							Map<String, Object> map1 = new HashMap<String, Object>();
							map1.put("id", a1.getId());// 区县ID
							map1.put("name", a1.getName());// 区县名称
							areaList.add(map1);
						}
					}
					map.put("areaList", areaList);
					dataList.add(map);
				}
			}
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 扶贫产品信息
	 * @param req
	 * @return
	 */
	@PostMapping("/povertyAlleviationDetail")
	@ResponseBody
	public ResJson povertyAlleviationDetail(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		try {
			if (StringUtils.isBlank(req.getString("areaId"))) {
				res.setResultNote("区县ID不能为空！");
				return res;
			}
			Area area = areaService.get(req.getString("areaId"));
			if (area == null) {
				res.setResultNote("区域不存在");
				return res;
			}
			Area city = areaService.get(area.getParentId());
			Area province = null;
			if (city != null) {
				province = areaService.get(city.getParentId());
			}
			TSupport support = new TSupport();
			support.setArea(new Area(req.getString("areaId")));
			List<TSupport> sList = tSupportService.findList(support);
			if (sList != null && sList.size() > 0) {
				res.put("image", getRealImage(sList.get(0).getImage()));
				res.put("title", sList.get(0).getTitle());
				res.put("video", getRealImage(sList.get(0).getVideo()));
				res.put("videoImage", getRealImage(sList.get(0).getVideoImage()));
				//res.put("content", sList.get(0).getContent());
				res.put("url", sList.get(0).getUrl());
			}
			// 商品列表
			List<Map<String, Object>> dataList = Lists.newArrayList();
			Product product = new Product();
			//product.setArea(new Area(req.getString("areaId")));
			product.setIsFupin("1");
			product.setAuditState("1");
			product.setState("0");
			/*product.setProvince(req.getString("province"));
			product.setCity(req.getString("city"));
			product.setDistrict(req.getString("district"));*/
			product.setProvince(province != null ? province.getName() : "");
			product.setCity(city != null ? city.getName() : "");
			product.setDistrict(area.getName());
			Page<Product> page = productService.findPage(new Page<Product>(req.getPageNo(), req.getPageSize()),
					product);
			for (Product n : page.getList()) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("productId", n.getId());
				map.put("coverImage", getRealImage(n.getIcon()));
				map.put("productName", n.getTitle());
				map.put("price", n.getPrice());
				map.put("originalPrice", n.getOldPrice());
				map.put("couponMoney", n.getDiscount());
				map.put("integral", n.getPoint());
				map.put("salesVolume", n.getSales());
				dataList.add(map);
			}
			res.setTotalPage(page.getTotalPage());
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 留言
	 * @param req
	 * @return
	 */
	@PostMapping("/leaveMessage")
	@ResponseBody
	public ResJson leaveMessage(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("留言失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("categoryName"))) {
				res.setResultNote("请选择商品分类！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("brand"))) {
				res.setResultNote("请选择商品品牌！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("model"))) {
				res.setResultNote("请输入商品型号！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("property"))) {
				res.setResultNote("请输入商品属性！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("cycle"))) {
				res.setResultNote("请输入周期！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("minPrice"))) {
				res.setResultNote("请输入预期最低价格！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("maxPrice"))) {
				res.setResultNote("请输入预期最高价格！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("time"))) {
				res.setResultNote("请选择时间！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("message"))) {
				res.setResultNote("请输入留言内容！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("province"))) {
				res.setResultNote("请选择省份！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("city"))) {
				res.setResultNote("请选择城市！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("area"))) {
				res.setResultNote("请选择区县！");
				return res;
			}
			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}
			Message m = new Message();
			m.setIsNewRecord(true);
			m.setId(IdGen.uuid());
			m.setMember(member);
			m.setCategory(req.getString("categoryName"));
			m.setBrand(req.getString("brand"));
			m.setModel(req.getString("model"));
			m.setProperty(req.getString("property"));
			m.setCycle(req.getString("cycle"));
			m.setMinPrice(req.getString("minPrice"));
			m.setMaxPrice(req.getString("maxPrice"));
			m.setChooseDate(new SimpleDateFormat("yyyy-MM-dd").parse(req.getString("time")));
			m.setContent(req.getString("message"));
			m.setProvince(req.getString("province"));
			m.setCity(req.getString("city"));
			m.setArea(req.getString("area"));
			m.setCreateDate(new Date());
			messageService.save(m);
			res.setResult("0");
			res.setResultNote("留言成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * top100商品列表
	 * @param req
	 * @return
	 */
	@PostMapping("/topProductList")
	@ResponseBody
	public ResJson topProductList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		try {
			// 商品列表
			Map<String, String> params = Maps.newHashMap();
			params.put("page", req.getPageNo() + "");// 分页获取数据,第几页
			params.put("page_size", req.getPageSize() + "");// 每页数据条数（默认每页20条），可自定义1-50之间
			params.put("sort", "new");// 按照返佣金额从高到低排序
			JSONObject jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_quantian, params);
			logger.debug("折淘客返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("status"))) {
				res.setResultNote(jsonObject.getString("content"));
				return res;
			}
			JSONArray dataList = jsonObject.getJSONArray("content");
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 限时秒杀
	 * @param req
	 * @return
	 */
	@PostMapping("/spikeList")
	@ResponseBody
	public ResJson spikeList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		if (StringUtils.isBlank(req.getString("hourType"))) {
			res.setResultNote("时间类型不能为空！");
			return res;
		}
		try {
			// 商品列表
			Map<String, String> params = Maps.newHashMap();
			params.put("page", req.getPageNo() + "");// 分页获取数据,第几页
			params.put("page_size", req.getPageSize() + "");// 每页数据条数（默认每页20条），可自定义1-50之间
			params.put("sort", "new");// 按照返佣金额从高到低排序
			params.put("t", req.getString("hourType"));// 按照时间段获取，值为空：全部咚咚抢商品，8-10：当日8点到10点之间咚咚抢商品，不包含10点及以后时间。
			JSONObject jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_dongdong, params);
			logger.debug("折淘客返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("status"))) {
				if("301".equals(jsonObject.getString("status"))){
					res.setResult("0");
				}
				res.setResultNote(jsonObject.getString("content"));
				return res;
			}
			JSONArray dataList = jsonObject.getJSONArray("content");
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 9块9包邮
	 * @param req
	 * @return
	 */
	@PostMapping("/shippingList")
	@ResponseBody
	public ResJson shippingList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		if (StringUtils.isBlank(req.getString("priceType"))) {
			res.setResultNote("价格类型为空！");
			return res;
		}
		try {
			Map<String, String> params = Maps.newHashMap();
			params.put("page", req.getPageNo() + "");// 分页获取数据,第几页
			params.put("page_size", req.getPageSize() + "");// 每页数据条数（默认每页20条），可自定义1-50之间
			if ("0".equals(req.getString("priceType"))) {// 9.9元区（9.9区展示大于6.9元，小于等于9.9的商品）
				params.put("price", "7.0-9.9");
			} else if ("1".equals(req.getString("priceType"))) {// 6.9元区（6.9区展示大于3.9元。小于等于6.9元的商品）
				params.put("price", "4.0-6.9");
			} else {// 3.9元区（3.9元区展示大于0，小于等于3.9元的商品）
				params.put("price", "0.0-3.9");
			}
			JSONObject jsonObject1 = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_all, params);
			logger.debug("折淘客返回数据：" + jsonObject1.toString());
			if (!"200".equals(jsonObject1.getString("status"))) {
				res.setResultNote(jsonObject1.getString("content"));
				return res;
			}
			JSONArray dataList = jsonObject1.getJSONArray("content");
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
    /**
     * 618活动
     * @param req
     * @return
     */
    @PostMapping("/sixhuneigList")
    @ResponseBody
    public ResJson sixhuneigList(@RequestBody ReqJson req) {
        ResJson res = new ResJson();
        res.setResultNote("查询失败");
        try {
            Map<String, String> params = Maps.newHashMap();
            params.put("page", req.getPageNo() + "");// 分页获取数据,第几页
            params.put("page_size", req.getPageSize() + "");// 每页数据条数（默认每页20条），可自定义1-50之间
            params.put("huodong", "618");

            JSONObject jsonObject1 = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_all, params);
            logger.debug("折淘客返回数据：" + jsonObject1.toString());
            if (!"200".equals(jsonObject1.getString("status"))) {
                res.setResultNote(jsonObject1.getString("content"));
                return res;
            }
            JSONArray dataList = jsonObject1.getJSONArray("content");
            res.setDataList(dataList);
            res.setResult("0");
            res.setResultNote("查询成功");
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return res;
    }

	/**
	 * 进入店铺页面信息
	 * @param req
	 * @return
	 */
	@PostMapping("/shopProductList")
	@ResponseBody
	public ResJson shopProductList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		try {
			if (StringUtils.isBlank(req.getString("shopId"))) {
				res.setResultNote("商家ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("sortType"))) {
				res.setResultNote("排序类型不能为空！");
				return res;
			}
			Store store=storeService.get(req.getString("shopId"));
			if(store==null){
				res.setResultNote("该店铺不存在！");
				return res;
			}
			res.put("shopName", store.getTitle());
			res.put("shopLogo", getRealImage(store.getIcon()));
			res.put("shopTele", store.getPhone());
			//商家综合评分
			/*StoreScore storeScore = new StoreScore();
			storeScore.setStore(store);
			List<StoreScore> sList = storeScoreService.findList(storeScore);
			int score = 0;
			if (sList != null && sList.size() > 0) {
				for (StoreScore s : sList) {
					score += s.getScore();
				}
			}
			res.put("score", score / sList.size());*/
			String score = storeScoreService.executeGetSql("SELECT IFNULL(SUM(score)/COUNT(*),0) FROM t_store_score WHERE store_id = '"+store.getId()+"'").toString();
			res.put("score", new BigDecimal(score).setScale(1, BigDecimal.ROUND_DOWN).toString());
			//是否收藏
			res.put("isCollect", "0");
			if(StringUtils.isNotBlank(req.getString("uid"))){
				CollectStore collectStore = new CollectStore();
				collectStore.setMember(new Member(req.getString("uid")));
				collectStore.setStore(store);
				List<CollectStore> cList = collectStoreService.findList(collectStore);
				if(cList != null && !cList.isEmpty()){
					res.put("isCollect", "1");
				}
			}

			// 商品列表
			List<Map<String, Object>> dataList = Lists.newArrayList();
			Product product = new Product();
			if(StringUtils.isNotBlank(req.getString("keyword"))){
				product.setTitle(req.getString("keyword"));
			}
			product.setStore(new Store(req.getString("shopId")));
			product.setAuditState("1");
			product.setState("0");
			Page<Product> page = productService.findPage(new Page<Product>(req.getPageNo(), req.getPageSize()),
					product);
			if ("1".equals(req.getString("sortType"))) {// 销量升序
				page.setOrderBy("a.sales ASC");
			} else if ("2".equals(req.getString("sortType"))) {// 销量降序
				page.setOrderBy("a.sales DESC");
			} else if ("3".equals(req.getString("sortType"))) {// 价格升序
				page.setOrderBy("a.price ASC");
			} else if ("4".equals(req.getString("sortType"))) {// 价格降序
				page.setOrderBy("a.price DESC");
			}
			for (Product n : page.getList()) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("productId", n.getId());
				map.put("coverImage", getRealImage(n.getIcon()));
				map.put("productName", n.getTitle());
				map.put("price", n.getPrice());
				map.put("originalPrice", n.getOldPrice());
				map.put("couponMoney", n.getDiscount());
				map.put("integral", n.getPoint());
				map.put("salesVolume", n.getSales());
				dataList.add(map);
			}
			res.setTotalPage(page.getTotalPage());
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 提交订单页面信息
	 * @param req
	 * @return
	 */
	@PostMapping("/confirmOrderInfo")
	@ResponseBody
	public ResJson confirmOrderInfo(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}
			Address address = new Address();
			address.setMember(member);
			address.setState("1");
			List<Address> aList = addressService.findList(address);
			if (aList != null && aList.size() > 0) {
				res.put("addrId", aList.get(0).getId());
				res.put("name", aList.get(0).getUsername());
				res.put("telephone", aList.get(0).getPhone());
				res.put("address", aList.get(0).getProvince() + aList.get(0).getCity() + aList.get(0).getArea()
						+ aList.get(0).getDetails());
			}
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 云店商品详情
	 * @param req
	 * @return
	 */
	@PostMapping("/cloudProductDetail")
	@ResponseBody
	public ResJson cloudProductDetail(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		try {
			if (StringUtils.isBlank(req.getString("productId"))) {
				res.setResultNote("商品ID不能为空！");
				return res;
			}
			Product product = productService.get(req.getString("productId"));
			if (product == null) {
				res.setResultNote("该商品不存在！");
				return res;
			}
			if ("1".equals(product.getState())) {
				res.setResultNote("该商品已下架！");
				return res;
			}
			List<String> images = new ArrayList<String>();
			if (StringUtils.isNotBlank(product.getImages())) {
				String[] image = product.getImages().split("\\|");
				for (String img : image) {
					images.add(getRealImage(img));
				}
				/*for (int i = 0; i < product.getImages().split("\\|").length; i++) {
					images.add(getRealImage(product.getImages().split("\\|")[i]));
				}*/
			}
			res.put("lbImageList", images);
			res.put("productCode", product.getCode());
			res.put("productName", product.getTitle());
			res.put("subTitle", product.getSubtitle());
			res.put("price", product.getPrice());
			res.put("giftprice", product.getGiftprice());
			res.put("originalPrice", product.getOldPrice());
			res.put("couponMoney", product.getDiscount());
			res.put("integral", product.getPoint());
			res.put("salesVolume", product.getSales());
			res.put("contentUrl", product.getContent());
			res.put("url", product.getUrl());
			res.put("shopId", product.getStore().getId());
			res.put("shopName", product.getStore().getTitle());
			res.put("shopLogo", getRealImage(product.getStore().getIcon()));
			res.put("isGroup", product.getIsGroup());
			res.put("isteprice", product.getIsteprice());
            res.put("tepricenum", product.getTepricenum());
			res.put("productLogo", getRealImage(product.getIcon()));
			res.put("categoryId", product.getCategory().getId());
			res.put("groupPrice", product.getGroupPrice());
			res.put("subsidyprice", product.getSubsidyprice());
			res.put("openprice", product.getOpenprice());
			res.put("shopPhone", product.getStore().getPhone());
			res.put("shangqiao", StringUtils.isNotBlank(product.getStore().getShangqiao()) ? StringEscapeUtils.unescapeHtml4(product.getStore().getShangqiao().trim()) : "");
			res.put("shopContent", product.getStore().getContent());
			res.put("ptRenNum", product.getPtRenNum());
			res.put("isMradd", product.getIsMradd());
			res.put("dlbt", product.getDlbt());
			res.put("isdl", product.getIsDl());
			res.put("isyg", product.getIsYg());
			res.put("ishot", product.getIsHot());
			res.put("isbd", product.getIsbd());
			res.put("ptfwmoney", product.getPtFwmoney());
			res.put("diff", product.getDiffprice());
			//根据商品查询规格属性
			List<ProductSkuname> psList = product.getProductSkunameList();
			List<Map<String, String>> skus = Lists.newArrayList();
			if(psList !=null && psList.size()>0){
				for(ProductSkuname ps:psList){
					Map<String, String> map = Maps.newHashMap();
					map.put("shuId", ps.getId());
					map.put("shuName", ps.getTitle());
					skus.add(map);
				}
			}
			res.put("shuList", skus);
			//规格列表
			List<Map<String, Object>> ggList = Lists.newArrayList();
			if (StringUtils.isNotBlank(req.getString("skuId"))) {
				ProductSku sku = productSkuService.get(req.getString("skuId"));
				if (sku != null) {
					Map<String, Object> map = Maps.newHashMap();
						map.put("id", sku.getId());
						map.put("specification", sku.getContent());
						map.put("oldPrice", sku.getOldPrice());
						map.put("discount", sku.getDiscount());
						map.put("price", sku.getPrice());
						map.put("groupPrice", sku.getGroupPrice());
						map.put("subsidyprice", sku.getSubsidyprice());
						map.put("openprice", sku.getOpenprice());
						map.put("point", sku.getPoint());
						map.put("stock", sku.getStock());
						map.put("image", getRealImage(sku.getImage()));
						ggList.add(map);
				}
			} else {
				ProductSku productSku = new ProductSku();
				productSku.setProduct(product);
				List<ProductSku> skuList = productSkuService.findList(productSku);
				for (ProductSku sku : skuList) {
					Map<String, Object> map = Maps.newHashMap();
						map.put("id", sku.getId());
						map.put("specification", sku.getContent());
						map.put("oldPrice", sku.getOldPrice());
						map.put("discount", sku.getDiscount());
						map.put("price", sku.getPrice());
						map.put("groupPrice", sku.getGroupPrice());
						map.put("subsidyprice", sku.getSubsidyprice());
						map.put("openprice", sku.getOpenprice());
						map.put("point", sku.getPoint());
						map.put("stock", sku.getStock());
						map.put("image", getRealImage(sku.getImage()));
						ggList.add(map);
				}//循环结束
			}

			res.put("ggList", ggList);

			List<Map<String, String>> giftList = Lists.newArrayList();// 赠品
			List<Map<String, String>> groupList = Lists.newArrayList();// 拼团
			if ("1".equals(product.getIsGroup())) {// 拼团商品
				// 查询赠品
				ProductGift productGift = new ProductGift();
				productGift.setProduct(product);
				List<ProductGift> productGiftList = productGiftService.findList(productGift);
				for (ProductGift gift : productGiftList) {
					Map<String, String> map = Maps.newHashMap();
					map.put("title", gift.getGift().getTitle());
					map.put("price", gift.getGift().getOldPrice());
					giftList.add(map);
				}
			}
			res.put("giftList", giftList);
			res.put("groupList", groupList);

			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 立即购买或购物车结算（下订单）
	 * @param req
	 * @return
	 */
	@PostMapping("/buyCommodity")
	@ResponseBody
	public synchronized ResJson buyCommodity(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("下单失败");
		try {
			if (StringUtils.isBlank(req.getUid())) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("addrId"))) {
				res.setResultNote("收货地址ID不能为空！");
				return res;
			}
			JSONArray shopList = req.getJSONArray("shopList");
			if(shopList == null || shopList.isEmpty()){
				res.setResultNote("商品不能为空！");
				return res;
			}
			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}

			Address addr = addressService.get(req.getString("addrId"));
			if (addr == null) {
				res.setResultNote("该收货地址不存在！");
				return res;
			}
			Member rec = null;

			String ordertaskid = null;// 用户拥有的的 购物币金额
			//对比专区产品是否超过优惠数
			if("1".equals(req.getString("isgwb"))){
				BigDecimal GWB = new BigDecimal(req.getString("gwbmoney"));// 用户选择的购物币金额
				BigDecimal GWBMoney = BigDecimal.ZERO;// 用户拥有的的 购物币金额
				List<WohuiEntity> entityList = Lists.newArrayList();
				entityList.add(new WohuiEntity("UGUID", member.getId()));
				JSONObject object5 = WohuiUtils.send(WohuiUtils.GetUInfoByGUID, entityList);
				if (!"0000".equals(object5.getString("respCode"))) {
					res.setResultNote(object5.getString("respMsg"));
					return res;
				}
				JSONArray data = object5.getJSONArray("data");
				JSONObject obj = data.getJSONObject(0);
				GWBMoney = new BigDecimal(obj.getString("C_BPQ"));
				if(obj.getIntValue("C_ZTOKNumNew") >= 10){
					if(GWBMoney.compareTo(GWB) < 0){ //GWBMoney小于等于0
						res.setResultNote("您的爆品购物券现在低于所优惠的金额，请重新选择！");
						return res;
					}
				}else { //GWBMoney小于等于0
					res.setResultNote("您的有效会员数不满足使用条件，不能使用爆品购物券！");
					return res;
				}
			}else if("2".equals(req.getString("isgwb"))){
				BigDecimal GWB = new BigDecimal(req.getString("gwbmoney"));// 用户选择的购物币金额
				BigDecimal GWBMoney = BigDecimal.ZERO;// 用户拥有的的 购物币金额
				List<WohuiEntity> entityList = Lists.newArrayList();
				entityList.add(new WohuiEntity("UGUID", member.getId()));
				JSONObject object5 = WohuiUtils.send(WohuiUtils.GetUInfoByGUID, entityList);
				if (!"0000".equals(object5.getString("respCode"))) {
					res.setResultNote(object5.getString("respMsg"));
					return res;
				}
				JSONArray data = object5.getJSONArray("data");
				JSONObject obj = data.getJSONObject(0);
				GWBMoney = new BigDecimal(obj.getString("C_XFQ"));
				if(GWBMoney.compareTo(GWB) < 0){ //GWBMoney小于0
					res.setResultNote("您的消费券现在低于所优惠的金额，请重新选择！");
					return res;
				}
			}else if("1".equals(req.getString("iszsq"))){
				BigDecimal ZSQ = new BigDecimal(req.getString("zsqmoney"));// 用户选择的专属券金额
				BigDecimal ZSQMoney = BigDecimal.ZERO;// 用户拥有的的 购物币金额
				List<WohuiEntity> entityList = Lists.newArrayList();
				entityList.add(new WohuiEntity("UGUID", member.getId()));
				JSONObject object5 = WohuiUtils.send(WohuiUtils.GetUInfoByGUID, entityList);
				if (!"0000".equals(object5.getString("respCode"))) {
					res.setResultNote(object5.getString("respMsg"));
					return res;
				}
				JSONArray data = object5.getJSONArray("data");
				JSONObject obj = data.getJSONObject(0);
				ZSQMoney = new BigDecimal(obj.getString("C_ZSQ"));
				if(ZSQMoney.compareTo(ZSQ) < 0){ //GWBMoney小于等于0
					res.setResultNote("您的专属券现在低于所优惠的金额，请重新选择！");
					return res;
				}
			}

			List<ProductOrder> orderList = Lists.newArrayList();
			List<Cart> cartList = Lists.newArrayList();

			if("1".equals(req.getString("isDaimai"))){//是代买
				if (StringUtils.isBlank(req.getString("telephone"))) {
					res.setResultNote("被代买手机号不能为空！");
					return res;
				}
				if (member.getPhone().equals(req.getString("telephone"))) {
					res.setResultNote("不能为自己代买");
					return res;
				}
				rec = memberService.getByPhone(req.getString("telephone"));
				List<WohuiEntity> entityList = Lists.newArrayList();
				entityList.add(new WohuiEntity("Phone", req.getString("telephone")));
				JSONObject object = WohuiUtils.send(WohuiUtils.GetUInfoByPhone, entityList);
				if (!"0000".equals(object.getString("respCode"))) {
					res.setResultNote("被代买手机号不存在");
					return res;
				}
				if (rec == null) {
					JSONArray jsonArray = object.getJSONArray("data");
					JSONObject whuser = jsonArray.getJSONObject(0);

					rec = new Member();
					rec.setIsNewRecord(true);
					rec.setId(whuser.getString("C_GUID"));
					rec.setNumber(whuser.getString("C_Number"));
					rec.setRoles(whuser.getString("C_Roles"));
					rec.setPhone(whuser.getString("C_Phone"));
					rec.setNickname(StringUtils.isNotBlank(whuser.getString("C_RealName")) ? whuser.getString("C_RealName") : "用户" + StringUtils.right(whuser.getString("C_Phone"), 4));
					rec.setPassword(whuser.getString("C_LoginPwd"));
					rec.setProvince(whuser.getString("C_Province"));
					rec.setCity(whuser.getString("C_City"));
					rec.setArea(whuser.getString("C_District"));
					rec.setState("0");
					rec.setPoint("0");
					rec.setInvite(new Member(whuser.getString("C_Sender")));
					memberService.save(rec);
				}
			}

			Product productDaili = null;
			if("1".equals(req.getString("isProxy"))){//是单品代理
				if (StringUtils.isBlank(req.getString("province"))) {
					res.setResultNote("请选择代理省份！");
					return res;
				}
				if (StringUtils.isBlank(req.getString("city"))) {
					res.setResultNote("请选择代理城市！");
					return res;
				}
				if (StringUtils.isBlank(req.getString("area"))) {
					res.setResultNote("请选择代理区县！");
					return res;
				}
				if (StringUtils.isBlank(req.getString("product"))) {
					res.setResultNote("请选择代理产品！");
					return res;
				}
				productDaili = productService.get(req.getString("product"));
				if (productDaili == null) {
					res.setResultNote("代理商品不存在");
					return res;
				}
			}
			// 大订单编号（主要用于多订单支付）
			String bigOrderNum = OrderNumPrefix.totalId + IdGen.getOrderNo();
			BigDecimal totalAmount = BigDecimal.ZERO;// 总金额

			for (int i = 0; i < shopList.size(); i++) {
				JSONObject shopObject = shopList.getJSONObject(i);
				Store shop = storeService.get(shopObject.getString("shopId"));
				if (shop == null || "1".equals(shop.getState()) || !"2".equals(shop.getAuditState())) {
					res.setResultNote("店铺不存在或被冻结");
					return res;
				}
				BigDecimal freight = BigDecimal.ZERO;// 店铺运费
				String ishot = "0";// 是否砍一刀专区
				if (StringUtils.isNotBlank(shop.getDistant())) {
					String[] distants = shop.getDistant().split(",");
					List<String> distantList = Arrays.asList(distants);
					if (distantList.contains(addr.getProvince()) && StringUtils.isNotBlank(shop.getFreight())) {
						freight = new BigDecimal(shop.getFreight());
					}
				}
				//新加,不在店铺配送区域内
				if(StringUtils.isNotBlank(shop.getNodelarea())){
					String[] nodelarea = shop.getNodelarea().split(",");
					List<String> distnodeList = Arrays.asList(nodelarea);
					if (distnodeList.contains(addr.getProvince())) {
						res.setResultNote(addr.getProvince()+"不在该店铺配送区域内");
						return res;
					}
				}

				JSONArray productList = shopObject.getJSONArray("productList");
				if(productList == null || productList.isEmpty()){
					res.setResultNote("店铺" + shop.getTitle() + "请选择商品");
					return res;
				}
				for(int j = 0; j < productList.size(); j++){
					List<OrderItem> orderItemList = Lists.newArrayList();// 订单项
					JSONObject object = productList.getJSONObject(j);

					BigDecimal totalMoney = BigDecimal.ZERO;// 订单总结算价
					BigDecimal price = BigDecimal.ZERO;// 商品总价
					BigDecimal amount = BigDecimal.ZERO;// 订单总额
					BigDecimal discount = BigDecimal.ZERO;// 商品优惠金额
					BigDecimal point = BigDecimal.ZERO;// 商品铜板
					BigDecimal totalFreight = BigDecimal.ZERO;// 订单运费
					BigDecimal hotPrice = BigDecimal.ZERO;// 爆品专区的快递费
					BigDecimal giftprice = BigDecimal.ZERO;// 赠品需支付价格
					BigDecimal kydprice = BigDecimal.ZERO;// 砍一刀专区的商品总价
					BigDecimal subsidyprice = BigDecimal.ZERO;// C2f专区补贴总价
					BigDecimal openprice = BigDecimal.ZERO;// C2f专区预售总价

					// 判断购物车结算还是直接购买
					if ("1".equals(req.getString("type"))) {// 1购物车结算 0直接购买
						Cart cart = cartService.get(object.getString("cartId"));
						if (cart == null) {
							res.setResultNote("购物车不存在");
							return res;
						}
						Product product = productService.get(cart.getProduct());
						if (product == null || "1".equals(product.getState()) || !"1".equals(product.getAuditState())) {
							res.setResultNote("购物车存在已下架商品");
							return res;
						}
						//新加,不在配送区域内
						if(StringUtils.isNotBlank(product.getNodelarea())){
							String[] nodelarea = product.getNodelarea().split(",");
							List<String> distnodeList = Arrays.asList(nodelarea);
							if (distnodeList.contains(addr.getProvince())) {
								res.setResultNote(addr.getProvince()+"不在该商品配送区域内");
								return res;
							}
						}

						//新加,特加商品判断
						if ( "1".equals(product.getIsteprice())) {
							String daimaiuid ="";
							String tsmsg ="";
							if("1".equals(req.getString("isDaimai"))){
								daimaiuid = rec.getId();
								tsmsg =",该代买账号已购买过此特价产品";
							}else{
								daimaiuid = member.getId();
								tsmsg =",该账号已购买过此特价产品";
							}
							List<Map<String,Object>> list = productOrderService.executeSelectSql("SELECT a.uid,a.state,a.id,i.product_id,i.order_id FROM t_product_order a LEFT JOIN t_order_item i on i.order_id=a.id WHERE a.uid='"+daimaiuid+"' AND i.product_id='"+product.getId()+"' AND a.state<5 AND a.state>0 ");
							if (list != null && !list.isEmpty()) {
								if (product.getTepricenum()<=1) {
									res.setResultNote("购物车存在产品为特价产品，每个会员仅限购买一次"+tsmsg);
									return res;
								}else if(list.size()>=product.getTepricenum()){
									res.setResultNote("本产品为特价产品，每个会员仅限购买"+product.getTepricenum()+"次"+tsmsg);
									return res;
								}
							}else {
								List<Map<String,Object>> list2 = productOrderService.executeSelectSql("SELECT a.uid,a.state,a.id,i.product_id,i.order_id FROM t_product_order a LEFT JOIN t_order_item i on i.order_id=a.id WHERE a.uid='"+daimaiuid+"' AND i.product_id='"+product.getId()+"' AND a.state=0 ");
								if (list2 != null && !list2.isEmpty()) {
									for (Map<String, Object> map : list2) {
										String state = map.get("state").toString();
										if ("0".equals(state)) {
											ProductOrder order = productOrderService.get(map.get("id").toString());
											order.setState("5");
											productOrderService.save(order);
											if("1".equals(order.getOrdertype())) {
												List<WohuiEntity> entityList = Lists.newArrayList();
												entityList.add(new WohuiEntity("OrderNO", order.getTotalId()));
												JSONObject result = WohuiUtils.send(WohuiUtils.XFQRefund, entityList);
												if (!"0000".equals(result.getString("respCode"))) {
													logger.error("我惠会员系统消费券下单取消订单失败总单号：" + order.getTotalId()+ result.getString("respMsg"));
												}
											}
											if("1".equals(order.getZsqtype())) {
												List<WohuiEntity> entityList = Lists.newArrayList();
												entityList.add(new WohuiEntity("OrderNO", order.getTotalId()));
												JSONObject result = WohuiUtils.send(WohuiUtils.ZSQRefund, entityList);
												if (!"0000".equals(result.getString("respCode"))) {
													logger.error("我惠会员系统专属券下单取消订单失败总单号：" + order.getTotalId()+ result.getString("respMsg"));
												}
											}
										}
									}
								}
							}
						}
						ProductSku sku = null;

						ProductSku productSku = new ProductSku();
						productSku.setProduct(product);
						List<ProductSku> productSkuList = productSkuService.findList(productSku);
						for (ProductSku productSku2 : productSkuList) {
							if (productSku2.getId().equals(cart.getSku().getId())) {
								sku = productSku2;
							}
						}
						if (sku == null) {
							res.setResultNote("商品" + product.getTitle() + "不存在规格");
							return res;
						}

						// 判断库存
						int qty = cart.getQty();
						int stock = sku.getStock();
						if (qty > stock) {
							res.setResultNote("商品" + product.getTitle() + "库存不足");
							return res;
						}

						//代理进货优惠判断   购物车判断（新加血德平复购判断）
						if("d4710c13050c490ab509ec0f81861868".equals(product.getId()) || "ecfadb9250204850b11ead9aa398df9d".equals(product.getId()) || "ca3dc0eb8ab04c59b98f6ff76ca9001b".equals(product.getId()) || "09978529550649b18cacee85ad7500ff".equals(product.getId())  || "15a62c70a1d74e34a059e74dde3336d8".equals(product.getId()) ){
							String daimaiuid ="";
							if("1".equals(req.getString("isDaimai"))){
								daimaiuid = rec.getId();
							}else{
								daimaiuid = member.getId();
							}
							List<WohuiEntity> entityList = Lists.newArrayList();
							entityList.add(new WohuiEntity("UGUID", daimaiuid));
							JSONObject object5 = WohuiUtils.send(WohuiUtils.GetUInfoByGUID, entityList);
							if (!"0000".equals(object5.getString("respCode"))) {
								res.setResultNote(object5.getString("respMsg"));
								return res;
							}
							JSONArray data = object5.getJSONArray("data");
							JSONObject obj = data.getJSONObject(0);
							String type10 ="0";
							String type20 ="0";
							String type30 ="0";
							String type31 ="0";
							if (StringUtils.isNotBlank(obj.getString("C_BHRebuy"))) {
								String[] BHRebuy = obj.getString("C_BHRebuy").split(",");
								List<String> rolesList = Arrays.asList(BHRebuy);
								if (rolesList.contains("10")) {
									type10 = "1";
								}
								if (rolesList.contains("20")) {
									type20 = "1";
								}
								if (rolesList.contains("30")) {
									type30 = "1";
								}
								if (rolesList.contains("31")) {
									type31 = "1";
								}
							}
							if("15a62c70a1d74e34a059e74dde3336d8".equals(product.getId()) && "0".equals(type10)){//	买一送一鬼谷回春堂压片糖果一盒30粒葛根代理进货
								res.setResultNote("您暂不能享受优惠购买此产品，请先选购代理订单！");
								return res;
							}
							if("09978529550649b18cacee85ad7500ff".equals(product.getId()) && "0".equals(type20)){//买一送一血德平葛参肽压片糖果一盒40片植物提取代理进货
								res.setResultNote("您暂不能享受优惠购买此产品，请先选购代理订单！");
								return res;
							}
							if("ecfadb9250204850b11ead9aa398df9d".equals(product.getId()) && "0".equals(type30)){//买一送一鸣鹤同舟酸康宝大盒装体验600克/盒代理进货
								res.setResultNote("您暂不能享受优惠购买此产品，请先选购代理订单！");
								return res;
							}
							if("ca3dc0eb8ab04c59b98f6ff76ca9001b".equals(product.getId()) && "0".equals(type31)){//买一送一鸣鹤同舟华蒜豆900克/盒固体饮料瓶装袋装代理进货
								res.setResultNote("您暂不能享受优惠购买此产品，请先选购代理订单！");
								return res;
							}
                            if("d4710c13050c490ab509ec0f81861868".equals(product.getId())) {
								if(object.getIntValue("count")>2){
									res.setResultNote("您本月最多可购买两件此产品，请重新选择购买数量！");
									return res;
								}
								if(object.getIntValue("count")<2){
									res.setResultNote("该产品单次购买不可少于两件，请重新选择购买数量！");
									return res;
								}
                                if ("True".equals(obj.getString("C_IsRebuyC"))) {//血德平复购判断
                                    List<Map<String, Object>> list = productOrderService.executeSelectSql("SELECT a.uid,a.state,a.id,i.product_id,i.order_id,i.qty FROM t_product_order a LEFT JOIN t_order_item i on i.order_id=a.id WHERE a.uid='" + daimaiuid + "' AND i.product_id='" + product.getId() + "'AND a.state<5 AND a.state>0 AND DATE_FORMAT( a.create_date, '%Y%m' ) = DATE_FORMAT( CURDATE( ) , '%Y%m' )");
                                    if (list != null && !list.isEmpty()) {
                                        if (list.size() >= 2) {
                                            res.setResultNote("您本月已享受此产品优惠，下个月可以继续享受哦，再看看其他产品吧！");
                                            return res;
                                        }
                                        int numsum = 0;
                                        for (Map<String, Object> map : list) {
                                            numsum += Integer.valueOf(map.get("qty").toString());
                                        }
                                        if (numsum >= 2) {
                                            res.setResultNote("您本月已享受此产品优惠，下个月可以继续享受哦，再看看其他产品吧！");
                                            return res;
                                        }
                                        if (object.getIntValue("count") + numsum > 2) {
                                            res.setResultNote("您本月最多可购买两件此产品，请重新选择购买数量！");
                                            return res;
                                        }
                                    }
                                }else{
                                    res.setResultNote("您暂不能享受优惠购买此产品！");
                                    return res;
                                }
                            }
						}
						totalMoney = totalMoney.add(new BigDecimal(sku.getAmount()).multiply(new BigDecimal(qty)));
						price = price.add(new BigDecimal(sku.getPrice()).multiply(new BigDecimal(qty)));
						giftprice = giftprice.add(new BigDecimal(product.getGiftprice()).multiply(new BigDecimal(qty)));//赠品需支付价格
						discount = discount.add(new BigDecimal(sku.getDiscount()).multiply(new BigDecimal(qty)));
						point = point.add(new BigDecimal(sku.getPoint()).multiply(new BigDecimal(qty)));//规格的铜板
						totalFreight = totalFreight.add(freight.multiply(new BigDecimal(qty)));
						if("1".equals(product.getIsHot())){
							ishot = "1";
						}
						if("1".equals(req.getString("isgwb"))){
							kydprice = kydprice.add(new BigDecimal(sku.getPrice()).multiply(new BigDecimal(qty)));//砍一刀专区
							hotPrice= hotPrice.add(new BigDecimal("10").multiply(new BigDecimal(qty)));
						}
						if("1".equals(req.getString("c2ftype"))){
							subsidyprice = subsidyprice.add(new BigDecimal(sku.getSubsidyprice()).multiply(new BigDecimal(qty)));//砍一刀专区
						}
						if("1".equals(req.getString("c2ftype"))){
							openprice = openprice.add(new BigDecimal(sku.getOpenprice()).multiply(new BigDecimal(qty)));//砍一刀专区
						}
						if("3".equals(product.getIsbd())){//爆品购物券兑换专区
							ishot = "1";
						}
						OrderItem item = new OrderItem();
						item.setId("");
						item.setProductId(product.getId());
						item.setSkuId(cart.getSku().getId());
						item.setProductCode(product.getCode());
						item.setProductTitle(product.getTitle());
						item.setProductIcon(product.getIcon());
						item.setIsDl(product.getIsDl());
						item.setIsYg(product.getIsYg());
						String goodstype="0";
						if("2".equals(product.getIsbd())){//惠淘好货
							goodstype="2";
						}else if("1".equals(product.getIscombo())){//套餐专区
							goodstype="1";
						}else if("4".equals(product.getIsbd())){//惠康优品
							goodstype="4";
						}else if("6".equals(product.getIsbd())){//C2F产品
							goodstype="6";
						}else if("7".equals(product.getIsbd())){//云店铺专区
							goodstype="7";
						}
						String Diffprice="0";
						if(product.getDiffprice() != null && !product.getDiffprice().isEmpty()){
							Diffprice =product.getDiffprice();
						}
						item.setDiffprice(new BigDecimal(Diffprice).toString());
						item.setGoodstype(goodstype);
						item.setSkuName(sku.getTitle());
						item.setQty(qty);
						item.setPrice(new BigDecimal(sku.getPrice()).multiply(new BigDecimal(qty)).toString());
						item.setPoint(new BigDecimal(sku.getPoint()).multiply(new BigDecimal(qty)).toString());
						item.setDiscount(new BigDecimal(sku.getDiscount()).multiply(new BigDecimal(qty)).toString());
						orderItemList.add(item);
						cartList.add(cart);
					} else {
						Product product = productService.get(object.getString("productId"));
						if (product == null || "1".equals(product.getState()) || !"1".equals(product.getAuditState())) {
							res.setResultNote("该商品不存在或已下架");
							return res;
						}
						//新加,不在配送区域内
						if(StringUtils.isNotBlank(product.getNodelarea())){
							String[] nodelarea = product.getNodelarea().split(",");
							List<String> distnodeList = Arrays.asList(nodelarea);
							if (distnodeList.contains(addr.getProvince())) {
								res.setResultNote(addr.getProvince()+"不在该商品配送区域内");
								return res;
							}
						}
						//新加,C2F产品任务判断  //
						if ( "6".equals(product.getIsbd()) && ("1".equals(req.getString("c2ftype")) || "2".equals(req.getString("c2ftype")))){
							List<Map<String,Object>> list = ordertaskService.executeSelectSql("SELECT uid,num,orderno,id,state,click_guid,click_icon,click_name FROM t_order_task WHERE uid='"+req.getString("uid")+"'and  productid='"+product.getId()+"'and state=1 AND expire_date > NOW() ORDER BY create_date DESC");
							if (list != null && !list.isEmpty()) {
								if(new BigDecimal(list.get(0).get("num").toString()).compareTo(new BigDecimal(5)) == -1){
									res.setResultNote("您的分享任务还未完成,暂不能以优惠价购买此产品");
									return res;
								}
								ordertaskid = list.get(0).get("id").toString();
							}else{
								res.setResultNote("您的分享任务还未完成,暂不能以优惠价购买此产品");
								return res;
							}
						}
						//新加,特价商品判断
						if ( "1".equals(product.getIsteprice())) {
							String daimaiuid ="";
							String tsmsg ="";
							if("1".equals(req.getString("isDaimai"))){
								daimaiuid = rec.getId();
								tsmsg =",该代买账号已购买过此产品";
							}else{
								daimaiuid = member.getId();
								tsmsg =",该账号已购买过此产品";
							}
							List<Map<String,Object>> list = productOrderService.executeSelectSql("SELECT a.uid,a.state,a.id,i.product_id,i.order_id FROM t_product_order a LEFT JOIN t_order_item i on i.order_id=a.id WHERE a.uid='"+daimaiuid+"' AND i.product_id='"+product.getId()+"' AND a.state<5 AND a.state>0 ");
							if (list != null && !list.isEmpty()) {
								if (product.getTepricenum()<=1) {
									res.setResultNote("购物车存在产品为特价产品，每个会员仅限购买一次"+tsmsg);
									return res;
								}else if(list.size()>=product.getTepricenum()){
									res.setResultNote("本产品为特价产品，每个会员仅限购买"+product.getTepricenum()+"次"+tsmsg);
									return res;
								}
							}else {
								List<Map<String,Object>> list2 = productOrderService.executeSelectSql("SELECT a.uid,a.state,a.id,i.product_id,i.order_id FROM t_product_order a LEFT JOIN t_order_item i on i.order_id=a.id WHERE a.uid='"+daimaiuid+"' AND i.product_id='"+product.getId()+"' AND a.state=0 ");
								if (list2 != null && !list2.isEmpty()) {
									for (Map<String, Object> map : list2) {
										String state = map.get("state").toString();
										if ("0".equals(state)) {
											ProductOrder order = productOrderService.get(map.get("id").toString());
											order.setState("5");
											productOrderService.save(order);
											if("1".equals(order.getOrdertype())) {
												List<WohuiEntity> entityList = Lists.newArrayList();
												entityList.add(new WohuiEntity("OrderNO", order.getTotalId()));
												JSONObject result = WohuiUtils.send(WohuiUtils.XFQRefund, entityList);
												if (!"0000".equals(result.getString("respCode"))) {
													logger.error("我惠会员系统消费券下单取消订单失败总单号：" + order.getTotalId()+ result.getString("respMsg"));
												}
											}
											if("1".equals(order.getZsqtype())) {
												List<WohuiEntity> entityList = Lists.newArrayList();
												entityList.add(new WohuiEntity("OrderNO", order.getTotalId()));
												JSONObject result = WohuiUtils.send(WohuiUtils.ZSQRefund, entityList);
												if (!"0000".equals(result.getString("respCode"))) {
													logger.error("我惠会员系统专属券下单取消订单失败总单号：" + order.getTotalId()+ result.getString("respMsg"));
												}
											}
										}
									}
								}
							}
						}
						ProductSku sku = null;
						ProductSku productSku = new ProductSku();
						productSku.setProduct(product);
						List<ProductSku> productSkuList = productSkuService.findList(productSku);
						for (ProductSku productSku2 : productSkuList) {
							if (productSku2.getId().equals(object.getString("ggId"))) {
								sku = productSku2;
							}
						}
						if (sku == null) {
							res.setResultNote("商品" + product.getTitle() + "不存在规格");
							return res;
						}

						// 判断库存
						int qty = object.getIntValue("count");
						int stock = sku.getStock();
						if (qty > stock) {
							res.setResultNote("商品" + product.getTitle() + "库存不足");
							return res;
						}
						//新加鬼谷回春堂，复购优惠判断
						if( "d4710c13050c490ab509ec0f81861868".equals(product.getId()) || "ecfadb9250204850b11ead9aa398df9d".equals(product.getId()) || "ca3dc0eb8ab04c59b98f6ff76ca9001b".equals(product.getId()) || "09978529550649b18cacee85ad7500ff".equals(product.getId())  || "15a62c70a1d74e34a059e74dde3336d8".equals(product.getId()) ){
							String daimaiuid ="";
							if("1".equals(req.getString("isDaimai"))){
								daimaiuid = rec.getId();
							}else{
								daimaiuid = member.getId();
							}
							List<WohuiEntity> entityList = Lists.newArrayList();
							entityList.add(new WohuiEntity("UGUID", daimaiuid));
							JSONObject object5 = WohuiUtils.send(WohuiUtils.GetUInfoByGUID, entityList);
							if (!"0000".equals(object5.getString("respCode"))) {
								res.setResultNote(object5.getString("respMsg"));
								return res;
							}
							JSONArray data = object5.getJSONArray("data");
							JSONObject obj = data.getJSONObject(0);
							String type10 ="0";
							String type20 ="0";
							String type30 ="0";
							String type31 ="0";
							if (StringUtils.isNotBlank(obj.getString("C_BHRebuy"))) {
								String[] BHRebuy = obj.getString("C_BHRebuy").split(",");
								List<String> rolesList = Arrays.asList(BHRebuy);
								if (rolesList.contains("10")) {
									type10 = "1";
								}
								if (rolesList.contains("20")) {
									type20 = "1";
								}
								if (rolesList.contains("30")) {
									type30 = "1";
								}
								if (rolesList.contains("31")) {
									type31 = "1";
								}
							}
							if("15a62c70a1d74e34a059e74dde3336d8".equals(product.getId()) && "0".equals(type10)){//	买一送一鬼谷回春堂压片糖果一盒30粒葛根代理进货
								res.setResultNote("您暂不能享受优惠购买此产品，请先选购代理订单！");
								return res;
							}
							if("09978529550649b18cacee85ad7500ff".equals(product.getId()) && "0".equals(type20)){//买一送一血德平葛参肽压片糖果一盒40片植物提取代理进货
								res.setResultNote("您暂不能享受优惠购买此产品，请先选购代理订单！");
								return res;
							}
							if("ecfadb9250204850b11ead9aa398df9d".equals(product.getId()) && "0".equals(type30)){//买一送一鸣鹤同舟酸康宝大盒装体验600克/盒代理进货
								res.setResultNote("您暂不能享受优惠购买此产品，请先选购代理订单！");
								return res;
							}
							if("ca3dc0eb8ab04c59b98f6ff76ca9001b".equals(product.getId()) && "0".equals(type31)){//买一送一鸣鹤同舟华蒜豆900克/盒固体饮料瓶装袋装代理进货
								res.setResultNote("您暂不能享受优惠购买此产品，请先选购代理订单！");
								return res;
							}
                            if("d4710c13050c490ab509ec0f81861868".equals(product.getId())) {
								if(object.getIntValue("count")>2){
									res.setResultNote("您本月最多可购买两件此产品，请重新选择购买数量！");
									return res;
								}
								if(object.getIntValue("count")<2){
									res.setResultNote("该产品单次购买不可少于两件，请重新选择购买数量！");
									return res;
								}
                                if ("True".equals(obj.getString("C_IsRebuyC"))) {//血德平复购判断
                                    List<Map<String, Object>> list = productOrderService.executeSelectSql("SELECT a.uid,a.state,a.id,i.product_id,i.order_id,i.qty FROM t_product_order a LEFT JOIN t_order_item i on i.order_id=a.id WHERE a.uid='" + daimaiuid + "' AND i.product_id='" + product.getId() + "'AND a.state<5 AND a.state>0 AND DATE_FORMAT( a.create_date, '%Y%m' ) = DATE_FORMAT( CURDATE( ) , '%Y%m' )");
                                    if (list != null && !list.isEmpty()) {
                                        if (list.size() >= 2) {
                                            res.setResultNote("您本月已享受此产品优惠，下个月可以继续享受哦，再看看其他产品吧！");
                                            return res;
                                        }
                                        int numsum = 0;
                                        for (Map<String, Object> map : list) {
                                            numsum += Integer.valueOf(map.get("qty").toString());
                                        }
                                        if (numsum >= 2) {
                                            res.setResultNote("您本月已享受此产品优惠，下个月可以继续享受哦，再看看其他产品吧！");
                                            return res;
                                        }
                                        if (object.getIntValue("count") + numsum > 2) {
                                            res.setResultNote("您本月最多可购买两件此产品，请重新选择购买数量！");
                                            return res;
                                        }
                                    }
                                }else{
                                    res.setResultNote("您暂不能享受优惠购买此产品！");
                                    return res;
                                }
                            }
						}
						totalMoney = totalMoney.add(new BigDecimal(sku.getAmount()).multiply(new BigDecimal(qty)));
						price = price.add(new BigDecimal(sku.getPrice()).multiply(new BigDecimal(qty)));
						giftprice = giftprice.add(new BigDecimal(product.getGiftprice()).multiply(new BigDecimal(qty)));//赠品需支付价格
						discount = discount.add(new BigDecimal(sku.getDiscount()).multiply(new BigDecimal(qty)));
						point = point.add(new BigDecimal(sku.getPoint()).multiply(new BigDecimal(qty)));//规格的铜板
						totalFreight = totalFreight.add(freight.multiply(new BigDecimal(qty)));
						if("1".equals(product.getIsHot())){
							ishot = "1";
						}
						if("1".equals(req.getString("isgwb"))){
							kydprice = kydprice.add(new BigDecimal(sku.getPrice()).multiply(new BigDecimal(qty)));//砍一刀专区
							hotPrice= hotPrice.add(new BigDecimal("10").multiply(new BigDecimal(qty)));
						}
						if("1".equals(req.getString("c2ftype"))){
							subsidyprice = subsidyprice.add(new BigDecimal(sku.getSubsidyprice()).multiply(new BigDecimal(qty)));//砍一刀专区
						}
						if("1".equals(req.getString("c2ftype"))){
							openprice = openprice.add(new BigDecimal(sku.getOpenprice()).multiply(new BigDecimal(qty)));//砍一刀专区
						}
						if("3".equals(product.getIsbd())){//爆品购物券兑换专区
							ishot = "1";
						}
						OrderItem item = new OrderItem();
						item.setId("");
						item.setProductId(product.getId());
						item.setSkuId(sku.getId());
						item.setProductCode(product.getCode());
						item.setProductTitle(product.getTitle());
						item.setProductIcon(product.getIcon());
						item.setIsDl(product.getIsDl());
						item.setIsYg(product.getIsYg());
						String goodstype="0";
						if("2".equals(product.getIsbd())){//惠淘好货
							goodstype="2";
						}else if("1".equals(product.getIscombo())){//套餐专区
							goodstype="1";
						}else if("4".equals(product.getIsbd())){//惠康优品
							goodstype="4";
						}else if("6".equals(product.getIsbd())){//C2F产品
							goodstype="6";
						}
						else if("7".equals(product.getIsbd())){//云店铺专区
							goodstype="7";
						}
						String Diffprice="0";
						if(product.getDiffprice() != null && !product.getDiffprice().isEmpty()){
							Diffprice =product.getDiffprice();
						}
						item.setDiffprice(new BigDecimal(Diffprice).toString());
						item.setGoodstype(goodstype);
						item.setSkuName(sku.getTitle());
						item.setQty(qty);
						item.setPrice(new BigDecimal(sku.getPrice()).multiply(new BigDecimal(qty)).toString());
						item.setPoint(new BigDecimal(sku.getPoint()).multiply(new BigDecimal(qty)).toString());
						item.setDiscount(new BigDecimal(sku.getDiscount()).multiply(new BigDecimal(qty)).toString());
						orderItemList.add(item);
					}

					ProductOrder productOrder = new ProductOrder();
					productOrder.setIsNewRecord(true);
					productOrder.setId(IdGen.getOrderNo());
					productOrder.setMember("1".equals(req.getString("isDaimai")) ? rec : member);
					productOrder.setDaimai("1".equals(req.getString("isDaimai")) ? member : null);
					productOrder.setStore(shop);
					productOrder.setTotalId(bigOrderNum);
					productOrder.setFreight(totalFreight.toString());
					productOrder.setGiftprice(giftprice.toString());//赠品需支付价格
					productOrder.setGwbprice(kydprice.toString());//购物币优惠价
					String cftype="0";
					Ordertask ordertask  = new Ordertask();
					productOrder.setOrdertype("0");
					if("1".equals(req.getString("isgwb"))){
						point = BigDecimal.ZERO;//使用爆品购物券就变成0铜板
						amount = amount.add(hotPrice);
					}else if("1".equals(req.getString("c2ftype"))){
						cftype="1";
						amount = amount.add(subsidyprice).add(totalFreight).add(giftprice);
						if(ordertaskid !=null && ordertaskid.isEmpty()){
							ordertask.setId(ordertaskid);
							ordertask.setState("2");
							ordertaskMapper.update(ordertask);
						}
					}else if("2".equals(req.getString("c2ftype"))){
						cftype="2";
						amount = amount.add(openprice).add(totalFreight).add(giftprice);
						if(ordertaskid !=null && ordertaskid.isEmpty()){
							ordertask.setId(ordertaskid);
							ordertask.setState("2");
							ordertaskMapper.update(ordertask);
						}
					}else if("2".equals(req.getString("isgwb"))){
						productOrder.setXfqprice(req.getString("gwbmoney"));//消费券优惠价
						productOrder.setOrdertype("1");
						if("1".equals(req.getString("iszsq"))){
                            productOrder.setZsqtype("1");
							productOrder.setZsqprice(req.getString("zsqmoney"));//专属价
							amount = amount.add(price).add(totalFreight).add(giftprice).subtract(new BigDecimal(req.getString("gwbmoney"))).subtract(new BigDecimal(req.getString("zsqmoney")));
						}else{
							amount = amount.add(price).add(totalFreight).add(giftprice).subtract(new BigDecimal(req.getString("gwbmoney")));
						}
					}else if("1".equals(req.getString("iszsq")) && !"2".equals(req.getString("isgwb"))){
						productOrder.setXfqprice("0");//消费券优惠价
						productOrder.setZsqprice(req.getString("zsqmoney"));//专属价
						productOrder.setZsqtype("1");
						amount = amount.add(price).add(totalFreight).add(giftprice).subtract(new BigDecimal(req.getString("zsqmoney")));
					}else{
						amount = amount.add(price).add(totalFreight).add(giftprice);
					}
					productOrder.setCftype(cftype);
					productOrder.setAmount(amount.toString());//订单总价
					productOrder.setMoney(totalMoney.add(totalFreight).add(giftprice).toString());// 订单结算价=商品结算价+运费+赠品需支付价格
					productOrder.setProxyType(req.getString("isProxy"));
					productOrder.setProxyPrice("0");
					productOrder.setUsername(addr.getUsername());
					productOrder.setPhone(addr.getPhone());
					productOrder.setProvince(addr.getProvince());
					productOrder.setCity(addr.getCity());
					productOrder.setMarea(addr.getArea());
					productOrder.setAddress(addr.getProvince() + addr.getCity() + addr.getArea() + addr.getDetails());
					if("2".equals(req.getString("c2ftype"))){
						productOrder.setState("8");
						productOrder.setExpiretaskDate(DateUtils.addDays(new Date(), 15));
					}else{
						productOrder.setState("0");
					}
					if(amount.compareTo(BigDecimal.ZERO) < 1 && ("2".equals(req.getString("isgwb")) || "1".equals(req.getString("iszsq")) )){
						productOrder.setState("1");
						productOrder.setPayType("3");
					}
					productOrder.setIsHot(ishot);
					productOrder.setRemarks(req.getString("remark"));
					productOrder.setReceipt(req.getString("invoice"));
					productOrder.setCreateDate(new Date());
					productOrder.setOrderItemList(orderItemList);
					productOrder.setPoint(point.toString());
					productOrder.setPrice(price.toString());
					productOrder.setDiscount(discount.toString());
					totalAmount = totalAmount.add(amount);
					if(!orderItemList.isEmpty()){
						orderList.add(productOrder);
					}
				}
			}
			productOrderService.insert(orderList);
			// 删除购物车
			if (!cartList.isEmpty()) {
				cartService.deleteAll(cartList);
			}
			if("1".equals(req.getString("isgwb"))){
				for (ProductOrder order: orderList) {
					// 购物币支付
					if ("1".equals(order.getIsHot()) && new BigDecimal(req.getString("gwbmoney")).compareTo(BigDecimal.ZERO)  > 0 ) {
						List<WohuiEntity> entityList = Lists.newArrayList();
						entityList.add(new WohuiEntity("OrderNO", order.getTotalId()));
						entityList.add(new WohuiEntity("CardGUID", member.getId()));
						entityList.add(new WohuiEntity("BPQ", req.getString("gwbmoney")));
						entityList.add(new WohuiEntity("Source", "YD"));
						entityList.add(new WohuiEntity("Remark", ""));
						JSONObject result = WohuiUtils.send(WohuiUtils.BPQPay, entityList);
						if (!"0000".equals(result.getString("respCode"))) {
							res.setResult("1");
							res.setResultNote("我惠会员系统爆品购物币大订单支付失败总单号：" +order.getTotalId()+ result.getString("respMsg"));
							return res;
						}
					}
				}
			}
			if("2".equals(req.getString("isgwb")) || "1".equals(req.getString("iszsq")) ){
				for (ProductOrder order: orderList) {
					// 消费券
					if ("1".equals(order.getOrdertype()) && new BigDecimal(req.getString("gwbmoney")).compareTo(BigDecimal.ZERO)  > 0 ) {
						List<WohuiEntity> entityList = Lists.newArrayList();
						entityList.add(new WohuiEntity("OrderNO", order.getTotalId()));
						entityList.add(new WohuiEntity("CardGUID", member.getId()));
						entityList.add(new WohuiEntity("XFQ", req.getString("gwbmoney")));
						entityList.add(new WohuiEntity("Source", "YD"));
						entityList.add(new WohuiEntity("Remark", ""));
						JSONObject result = WohuiUtils.send(WohuiUtils.XFQPay, entityList);
						if (!"0000".equals(result.getString("respCode"))) {
							res.setResult("1");
							res.setResultNote("我惠会员系统消费券大订单支付失败总单号：" +order.getTotalId()+ result.getString("respMsg"));
							return res;
						}
					}
					// 专属券
					if ("1".equals(order.getZsqtype()) && new BigDecimal(req.getString("zsqmoney")).compareTo(BigDecimal.ZERO)  > 0 ) {
						List<WohuiEntity> entityList = Lists.newArrayList();
						entityList.add(new WohuiEntity("OrderNO", order.getTotalId()));
						entityList.add(new WohuiEntity("CardGUID", member.getId()));
						entityList.add(new WohuiEntity("ZSQ", req.getString("zsqmoney")));
						entityList.add(new WohuiEntity("Source", "YD"));
						entityList.add(new WohuiEntity("Remark", ""));
						JSONObject result = WohuiUtils.send(WohuiUtils.ZSQPay, entityList);
						if (!"0000".equals(result.getString("respCode"))) {
							res.setResult("1");
							res.setResultNote("我惠会员系统专属券大订单支付失败总单号：" +order.getTotalId()+ result.getString("respMsg"));
							return res;
						}
					}
					if(new BigDecimal(order.getAmount()).compareTo(BigDecimal.ZERO) == 0){
						ProductOrder productOrder = productOrderService.get(order.getId());
						productOrder.setPayDate(new Date());
						productOrderService.pay(productOrder);
					}
				}
			}

			res.put("orderNum", bigOrderNum);
			res.put("amount", totalAmount.toString());
			res.setResult("0");
			res.setResultNote("下单成功");
		} catch (Exception e) {
			e.printStackTrace();
			res.setResultNote(e.getMessage());
			logger.error(e.getMessage());
		}
		return res;
	}
	/*************************小程序**********************************/
	/**
	 * 拼多多首页一分类
	 * @param req
	 * @return
	 */
	@PostMapping("/pinduoduoCategory")
	@ResponseBody
	public ResJson pinduoduoCategory(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		try {
			List<Map<String, Object>> categoryList = Lists.newArrayList();
			PddCategory pddCategory = new PddCategory();
			pddCategory.setState("0");
			List<PddCategory> pddcategoryList = pddCategoryService.findList(pddCategory);
			for (PddCategory cagegory : pddcategoryList) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", cagegory.getId());
				map.put("name", cagegory.getName());
				map.put("icon", getRealImage(cagegory.getIcon()));
				categoryList.add(map);
			}
			res.put("categoryList", categoryList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
/*************************小程序**********************************/
	/*************************重新写的**********************************/
	/**
	 * 查询首页淘客一分类
	 * @param req
	 * @return
	 */
	@PostMapping("/findAmoyCategory")
	@ResponseBody
	public ResJson findAmoyCategory(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		try {
			// 一级分类列表
			/*List<Map<String, Object>> dataList = Lists.newArrayList();
			JSONObject jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_type, Maps.newHashMap());
			logger.debug("折淘客返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("status"))) {
				res.setResultNote(jsonObject.getString("content"));
				return res;
			}
			JSONArray dataArray = jsonObject.getJSONArray("type");
			if (dataArray != null) {
				for (int i = 0; i < dataArray.size(); i++) {
					JSONObject c = dataArray.getJSONObject(i);
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("id", c.get("cid"));
					map.put("name", c.get("name"));
					map.put("icon", c.get("q_pic"));
					dataList.add(map);
				}
			}*/
			List<Map<String, Object>> dataList = apiService.findAmoyCategory();
			res.setDataList(removeRepeatMapByKey(dataList, "id"));
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 查询淘客二级分类
	 * @param req
	 * @return
	 */
	@PostMapping("/findAmoyEjCategory")
	@ResponseBody
	public ResJson findAmoyEjCategory(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		if (StringUtils.isBlank(req.getString("categoryId"))) {
			res.setResultNote("分类ID不能为空！");
			return res;
		}
		try {
			// 一级分类列表
			List<Map<String, Object>> dataList = Lists.newArrayList();
			JSONObject jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_type, Maps.newHashMap());
			logger.debug("折淘客返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("status"))) {
				res.setResultNote(jsonObject.getString("content"));
				return res;
			}
			JSONArray dataArray = jsonObject.getJSONArray("type");
			if (dataArray != null) {
				for (int i = 0; i < dataArray.size(); i++) {
					JSONObject c = dataArray.getJSONObject(i);
					Map<String, Object> map = new HashMap<String, Object>();
					if(req.getString("categoryId").equals(c.get("cid"))){
						map.put("id", c.get("cid"));
						map.put("name", c.get("q"));
						map.put("icon", c.get("q_pic"));
						dataList.add(map);
					}
				}
			}
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 根据一二级分类ID查询淘客商品列表
	 * @param req
	 * @return
	 */
	@PostMapping("/findAmoyProductListByCategory")
	@ResponseBody
	public ResJson findAmoyProductListByCategory(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		if (StringUtils.isBlank(req.getString("categoryId"))) {
			res.setResultNote("分类ID不能为空！");
			return res;
		}
		if (StringUtils.isBlank(req.getString("sortType"))) {
			res.setResultNote("排序类型不能为空！");
			return res;
		}
		try {
			Map<String, String> params = Maps.newHashMap();
			params.put("page", req.getPageNo() + "");// 分页获取数据,第几页
			params.put("page_size", req.getPageSize() + "");// 每页数据条数（默认每页20条），可自定义1-50之间
			params.put("cid", req.getString("categoryId"));
			if (StringUtils.isNotBlank(req.getString("name"))) {
				params.put("q", req.getString("name"));
			}
			// 排序类型:0-综合，1-销量升序，2-销量降序，3-价格升序，4-价格降序,5-铜板升序，6-铜板降序
			if ("1".equals(req.getString("sortType"))) {
				params.put("sort", "sale_num_asc");
			} else if ("2".equals(req.getString("sortType"))) {
				params.put("sort", "sale_num_desc");
			} else if ("3".equals(req.getString("sortType"))) {
				params.put("sort", "price_asc");
			} else if ("4".equals(req.getString("sortType"))) {
				params.put("sort", "price_desc");
			} else if ("5".equals(req.getString("sortType"))) {
				params.put("sort", "tkfee_asc");
			} else if ("6".equals(req.getString("sortType"))) {
				params.put("sort", "tkfee_desc");
			} else {
				params.put("sort", "new");
			}
			JSONObject jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_all, params);
			logger.debug("折淘客返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("status"))) {
				res.setResultNote(jsonObject.getString("content"));
				return res;
			}
			JSONArray dataList = jsonObject.getJSONArray("content");
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 我惠逛街
	 * @param req
	 * @return
	 */
	@PostMapping("/shopping")
	@ResponseBody
	public ResJson shopping(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		try {
			Access a1 = accessService.findUniqueByProperty("type", "6");
			res.put("clothingImage", getRealImage(a1.getImage()));
			Access a2 = accessService.findUniqueByProperty("type", "7");
			res.put("businessImage", getRealImage(a2.getImage()));
			// 轮播图列表
			List<Map<String, Object>> bannerList = Lists.newArrayList();
			Banner banner = new Banner();
			banner.setType("3");
			List<Banner> list = bannerService.findList(banner);
			for (Banner b : list) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("image", getRealImage(b.getImage()));
				map.put("category", b.getCategory());
				map.put("url", b.getUrl());
				map.put("productId", b.getProduct() != null ? b.getProduct().getId() : "");
				map.put("storeId", b.getStore() != null ? b.getStore().getId() : "");
				map.put("thirdLink", StringUtils.isNotBlank(b.getThirdLink()) ? b.getThirdLink() : "");
				map.put("productCategoryId", b.getProductCategory() != null ? b.getProductCategory().getId() : "");
				map.put("productCategoryName", b.getProductCategory() != null ? b.getProductCategory().getName() : "");
				bannerList.add(map);
			}
			res.put("bannerList", bannerList);
			// 商品列表
			Map<String, String> params = Maps.newHashMap();
			params.put("page", req.getPageNo() + "");// 分页获取数据,第几页
			params.put("page_size", req.getPageSize() + "");// 每页数据条数（默认每页20条），可自定义1-50之间
			params.put("q", "服装");
			params.put("sort", "commission_rate_desc");// 按照佣金比例从大到小排序
			/*params.put("youquan", "1");// 按照佣金比例从大到小排序
*/			params.put("start_tk_rate", "20");// 淘客佣金比率下限。如：输入20，表示大于等于20%
			JSONObject jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_quanwang, params);
			logger.debug("折淘客返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("status"))) {
				res.setResultNote(jsonObject.getString("content"));
				return res;
			}
			JSONArray dataList = jsonObject.getJSONArray("content");
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 我惠逛街精品服装分类列表
	 * @param req
	 * @return
	 */
	@PostMapping("/clothingCategoryList")
	@ResponseBody
	public ResJson clothingCategoryList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		try {
			// 二级分类列表
			List<Map<String, Object>> dataList = Lists.newArrayList();
			JSONObject jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_type, Maps.newHashMap());
			logger.debug("折淘客返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("status"))) {
				res.setResultNote(jsonObject.getString("content"));
				return res;
			}
			JSONArray dataArray = jsonObject.getJSONArray("type");
			if (dataArray != null) {
				for (int i = 0; i < dataArray.size(); i++) {
					JSONObject c = dataArray.getJSONObject(i);
					Map<String, Object> map = new HashMap<String, Object>();
					if ("1".equals(c.get("cid"))) {
						map.put("id", c.get("cid"));
						map.put("name", c.get("q"));
						map.put("icon", c.get("q_pic"));
						dataList.add(map);
					}
				}
			}
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 我惠逛街根据服装分类名称查询商品列表
	 * @param req
	 * @return
	 */
	@PostMapping("/findByClothingCategoryId")
	@ResponseBody
	public ResJson findByClothingCategoryId(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		if (StringUtils.isBlank(req.getString("name"))) {
			res.setResultNote("分类名称不能为空！");
			return res;
		}
		try {
			Map<String, String> params = Maps.newHashMap();
			params.put("page", req.getPageNo() + "");// 分页获取数据,第几页
			params.put("page_size", req.getPageSize() + "");// 每页数据条数（默认每页20条），可自定义1-50之间
			params.put("cid", "1");// 一级商品分类，值为空：全部商品，1：女装，2：母婴，3：美妆，4：居家日用，5：鞋品，6：美食，7：文娱车品，8：数码家电，9：男装，10：内衣，11：箱包，12：配饰，13：户外运动，14：家装家纺
			params.put("q", req.getString("name"));// 二级商品分类，值为空：全部商品，其它值请参考二级分类接口数据，比如外套，连衣裙等
			JSONObject jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_all, params);
			logger.debug("折淘客返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("status"))) {
				res.setResultNote(jsonObject.getString("content"));
				return res;
			}
			JSONArray dataList = jsonObject.getJSONArray("content");
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 我惠美食
	 * @param req
	 * @return
	 */
	@PostMapping("/food")
	@ResponseBody
	public ResJson food(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		try {
			// 轮播图列表
			List<Map<String, Object>> bannerList = Lists.newArrayList();
			Banner banner = new Banner();
			banner.setType("4");
			List<Banner> list = bannerService.findList(banner);
			for (Banner b : list) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("image", getRealImage(b.getImage()));
				map.put("category", b.getCategory());
				map.put("url", b.getUrl());
				map.put("productId", b.getProduct() != null ? b.getProduct().getId() : "");
				map.put("storeId", b.getStore() != null ? b.getStore().getId() : "");
				map.put("thirdLink", StringUtils.isNotBlank(b.getThirdLink()) ? b.getThirdLink() : "");
				map.put("productCategoryId", b.getProductCategory() != null ? b.getProductCategory().getId() : "");
				map.put("productCategoryName", b.getProductCategory() != null ? b.getProductCategory().getName() : "");
				bannerList.add(map);
			}
			res.put("bannerList", bannerList);
			// 美食分类列表
			List<Map<String, Object>> categoryList = Lists.newArrayList();
			JSONObject jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_type, Maps.newHashMap());
			logger.debug("折淘客返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("status"))) {
				res.setResultNote(jsonObject.getString("content"));
				return res;
			}
			JSONArray dataArray = jsonObject.getJSONArray("type");
			if (dataArray != null) {
				for (int i = 0; i < dataArray.size(); i++) {
					JSONObject c = dataArray.getJSONObject(i);
					Map<String, Object> map = new HashMap<String, Object>();
					if ("6".equals(c.get("cid"))) {
						map.put("id", c.get("cid"));
						map.put("name", c.get("q"));
						map.put("icon", c.get("q_pic"));
						categoryList.add(map);
					}
				}
			}
			res.put("categoryList", categoryList);
			// 商品列表
			Map<String, String> params = Maps.newHashMap();
			params.put("page", req.getPageNo() + "");// 分页获取数据,第几页
			params.put("page_size", req.getPageSize() + "");// 每页数据条数（默认每页20条），可自定义1-50之间
			params.put("cid", "6");// 一级商品分类，值为空：全部商品，1：女装，2：母婴，3：美妆，4：居家日用，5：鞋品，6：美食，7：文娱车品，8：数码家电，9：男装，10：内衣，11：箱包，12：配饰，13：户外运动，14：家装家纺
			// 排序类型:0-综合，1-销量升序，2-销量降序，3-价格升序，4-价格降序,5-铜板升序，6-铜板降序
			if ("1".equals(req.getString("sortType"))) {
				params.put("sort", "sale_num_asc");
			} else if ("2".equals(req.getString("sortType"))) {
				params.put("sort", "sale_num_desc");
			} else if ("3".equals(req.getString("sortType"))) {
				params.put("sort", "price_asc");
			} else if ("4".equals(req.getString("sortType"))) {
				params.put("sort", "price_desc");
			} else if ("5".equals(req.getString("sortType"))) {
				params.put("sort", "tkfee_asc");
			} else if ("6".equals(req.getString("sortType"))) {
				params.put("sort", "tkfee_desc");
			} else {
				params.put("sort", "new");
			}
			JSONObject jsonObject1 = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_all, params);
			logger.debug("折淘客返回数据：" + jsonObject1.toString());
			if (!"200".equals(jsonObject1.getString("status"))) {
				res.setResultNote(jsonObject1.getString("content"));
				return res;
			}
			JSONArray dataList = jsonObject1.getJSONArray("content");
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 我惠美食根据分类ID查询商品列表
	 * @param req
	 * @return
	 */
	@PostMapping("/findFoodListByCategoryId")
	@ResponseBody
	public ResJson findFoodListByCategoryId(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		if (StringUtils.isBlank(req.getString("name"))) {
			res.setResultNote("分类名称不能为空！");
			return res;
		}
		if (StringUtils.isBlank(req.getString("sortType"))) {
			res.setResultNote("排序类型不能为空！");
			return res;
		}
		try {
			// 商品列表
			Map<String, String> params = Maps.newHashMap();
			params.put("page", req.getPageNo() + "");// 分页获取数据,第几页
			params.put("page_size", req.getPageSize() + "");// 每页数据条数（默认每页20条），可自定义1-50之间
			params.put("q", req.getString("name"));
			// 排序类型:0-综合，1-销量升序，2-销量降序，3-价格升序，4-价格降序,5-铜板升序，6-铜板降序
			if ("1".equals(req.getString("sortType"))) {
				params.put("sort", "sale_num_asc");
			} else if ("2".equals(req.getString("sortType"))) {
				params.put("sort", "sale_num_desc");
			} else if ("3".equals(req.getString("sortType"))) {
				params.put("sort", "price_asc");
			} else if ("4".equals(req.getString("sortType"))) {
				params.put("sort", "price_desc");
			} else if ("5".equals(req.getString("sortType"))) {
				params.put("sort", "tkfee_asc");
			} else if ("6".equals(req.getString("sortType"))) {
				params.put("sort", "tkfee_desc");
			} else {
				params.put("sort", "new");
			}
			JSONObject jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_all, params);
			logger.debug("折淘客返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("status"))) {
				res.setResultNote(jsonObject.getString("content"));
				return res;
			}
			JSONArray dataList = jsonObject.getJSONArray("content");
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 淘宝
	 * @param req
	 * @return
	 */
	@PostMapping("/taobaoIndex")
	@ResponseBody
	public ResJson taobaoIndex(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		if (StringUtils.isBlank(req.getString("sortType"))) {
			res.setResultNote("排序类型不能为空！");
			return res;
		}
		try {
			// 轮播图列表
			List<Map<String, Object>> bannerList = Lists.newArrayList();
			Banner banner = new Banner();
			banner.setType("7");
			List<Banner> list = bannerService.findList(banner);
			for (Banner b : list) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("image", getRealImage(b.getImage()));
				map.put("category", b.getCategory());
				map.put("url", b.getUrl());
				map.put("productId", b.getProduct() != null ? b.getProduct().getId() : "");
				map.put("storeId", b.getStore() != null ? b.getStore().getId() : "");
				map.put("thirdLink", StringUtils.isNotBlank(b.getThirdLink()) ? b.getThirdLink() : "");
				map.put("productCategoryId", b.getProductCategory() != null ? b.getProductCategory().getId() : "");
				map.put("productCategoryName", b.getProductCategory() != null ? b.getProductCategory().getName() : "");
				bannerList.add(map);
			}
			res.put("bannerList", bannerList);
			// 分类列表
			List<Map<String, Object>> categoryList = Lists.newArrayList();
			JSONObject jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_type, Maps.newHashMap());
			logger.debug("折淘客返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("status"))) {
				res.setResultNote(jsonObject.getString("content"));
				return res;
			}
			JSONArray dataArray = jsonObject.getJSONArray("type");
			if (dataArray != null) {
				for (int i = 0; i < dataArray.size(); i++) {
					JSONObject c = dataArray.getJSONObject(i);
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("id", c.get("cid"));
					map.put("name", c.get("name"));
					map.put("icon", c.get("q_pic"));
					categoryList.add(map);
				}
			}
			res.put("categoryList", removeRepeatMapByKey(categoryList, "id"));
			// 商品列表
			Map<String, String> params = Maps.newHashMap();
			params.put("page", req.getPageNo() + "");// 分页获取数据,第几页
			params.put("page_size", req.getPageSize() + "");// 每页数据条数（默认每页20条），可自定义1-50之间
			params.put("tj", "taobao");
			// 排序类型:0-综合，1-销量升序，2-销量降序，3-价格升序，4-价格降序,5-铜板升序，6-铜板降序
			if ("1".equals(req.getString("sortType"))) {
				params.put("sort", "sale_num_asc");
			} else if ("2".equals(req.getString("sortType"))) {
				params.put("sort", "sale_num_desc");
			} else if ("3".equals(req.getString("sortType"))) {
				params.put("sort", "price_asc");
			} else if ("4".equals(req.getString("sortType"))) {
				params.put("sort", "price_desc");
			} else if ("5".equals(req.getString("sortType"))) {
				params.put("sort", "tkfee_asc");
			} else if ("6".equals(req.getString("sortType"))) {
				params.put("sort", "tkfee_desc");
			} else {
				params.put("sort", "new");
			}
			JSONObject jsonObject1 = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_all, params);
			logger.debug("折淘客返回数据：" + jsonObject1.toString());
			if (!"200".equals(jsonObject1.getString("status"))) {
				res.setResultNote(jsonObject1.getString("content"));
				return res;
			}
			JSONArray dataList = jsonObject1.getJSONArray("content");
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 淘宝根据分类ID查询商品列表
	 * @param req
	 * @return
	 */
	@PostMapping("/taobaoProductList")
	@ResponseBody
	public ResJson taobaoProductList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		if (StringUtils.isBlank(req.getString("categoryId"))) {
			res.setResultNote("分类ID不能为空！");
			return res;
		}
		if (StringUtils.isBlank(req.getString("sortType"))) {
			res.setResultNote("排序类型不能为空！");
			return res;
		}
		try {
			// 商品列表
			Map<String, String> params = Maps.newHashMap();
			params.put("page", req.getPageNo() + "");// 分页获取数据,第几页
			params.put("page_size", req.getPageSize() + "");// 每页数据条数（默认每页20条），可自定义1-50之间
			params.put("cid", req.getString("categoryId"));
			params.put("tj", "taobao");
			// 排序类型:0-综合，1-销量升序，2-销量降序，3-价格升序，4-价格降序,5-铜板升序，6-铜板降序
			if ("1".equals(req.getString("sortType"))) {
				params.put("sort", "sale_num_asc");
			} else if ("2".equals(req.getString("sortType"))) {
				params.put("sort", "sale_num_desc");
			} else if ("3".equals(req.getString("sortType"))) {
				params.put("sort", "price_asc");
			} else if ("4".equals(req.getString("sortType"))) {
				params.put("sort", "price_desc");
			} else if ("5".equals(req.getString("sortType"))) {
				params.put("sort", "tkfee_asc");
			} else if ("6".equals(req.getString("sortType"))) {
				params.put("sort", "tkfee_desc");
			} else {
				params.put("sort", "new");
			}
			JSONObject jsonObject1 = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_all, params);
			logger.debug("折淘客返回数据：" + jsonObject1.toString());
			if (!"200".equals(jsonObject1.getString("status"))) {
				res.setResultNote(jsonObject1.getString("content"));
				return res;
			}
			JSONArray dataList = jsonObject1.getJSONArray("content");
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 跨境优选
	 * @param req
	 * @return
	 */
	@PostMapping("/kuajingIndex")
	@ResponseBody
	public ResJson kuajingIndex(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		try {
			// banner图
			Access access = accessService.findUniqueByProperty("type", "5");
			if (access != null) {
				res.put("image", getRealImage(access.getImage()));
			}
			// 分类列表
			List<Map<String, Object>> categoryList = Lists.newArrayList();
			JSONObject jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_type, Maps.newHashMap());
			logger.debug("折淘客返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("status"))) {
				res.setResultNote(jsonObject.getString("content"));
				return res;
			}
			JSONArray dataArray = jsonObject.getJSONArray("type");
			if (dataArray != null) {
				for (int i = 0; i < dataArray.size(); i++) {
					JSONObject c = dataArray.getJSONObject(i);
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("id", c.get("cid"));
					map.put("name", c.get("name"));
					map.put("icon", c.get("q_pic"));
					categoryList.add(map);
				}
			}
			res.put("categoryList", removeRepeatMapByKey(categoryList, "id"));
			// 商品列表
			Map<String, String> params = Maps.newHashMap();
			params.put("page", req.getPageNo() + "");// 分页获取数据,第几页
			params.put("page_size", req.getPageSize() + "");// 每页数据条数（默认每页20条），可自定义1-50之间
			params.put("jh", "haitao");// 海淘或者极有家，值为空：全部商品，haitao：海淘商品，jiyoujia：极有家商品
			// 排序类型:0-综合，1-销量升序，2-销量降序，3-价格升序，4-价格降序,5-铜板升序，6-铜板降序
			if ("1".equals(req.getString("sortType"))) {
				params.put("sort", "sale_num_asc");
			} else if ("2".equals(req.getString("sortType"))) {
				params.put("sort", "sale_num_desc");
			} else if ("3".equals(req.getString("sortType"))) {
				params.put("sort", "price_asc");
			} else if ("4".equals(req.getString("sortType"))) {
				params.put("sort", "price_desc");
			} else if ("5".equals(req.getString("sortType"))) {
				params.put("sort", "tkfee_asc");
			} else if ("6".equals(req.getString("sortType"))) {
				params.put("sort", "tkfee_desc");
			} else {
				params.put("sort", "new");
			}
			JSONObject jsonObject1 = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_all, params);
			logger.debug("折淘客返回数据：" + jsonObject1.toString());
			if (!"200".equals(jsonObject1.getString("status"))) {
				res.setResultNote(jsonObject1.getString("content"));
				return res;
			}
			JSONArray dataList = jsonObject1.getJSONArray("content");
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 跨境优选根据分类ID查询商品列表
	 * @param req
	 * @return
	 */
	@PostMapping("/kjProductList")
	@ResponseBody
	public ResJson kjProductList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		if (StringUtils.isBlank(req.getString("categoryId"))) {
			res.setResultNote("分类ID不能为空！");
			return res;
		}
		if (StringUtils.isBlank(req.getString("sortType"))) {
			res.setResultNote("排序类型不能为空！");
			return res;
		}
		try {
			// 商品列表
			Map<String, String> params = Maps.newHashMap();
			params.put("page", req.getPageNo() + "");// 分页获取数据,第几页
			params.put("page_size", req.getPageSize() + "");// 每页数据条数（默认每页20条），可自定义1-50之间
			params.put("cid", req.getString("categoryId"));// 每页数据条数（默认每页20条），可自定义1-50之间
			// 排序类型:0-综合，1-销量升序，2-销量降序，3-价格升序，4-价格降序,5-铜板升序，6-铜板降序
			if ("1".equals(req.getString("sortType"))) {
				params.put("sort", "sale_num_asc");
			} else if ("2".equals(req.getString("sortType"))) {
				params.put("sort", "sale_num_desc");
			} else if ("3".equals(req.getString("sortType"))) {
				params.put("sort", "price_asc");
			} else if ("4".equals(req.getString("sortType"))) {
				params.put("sort", "price_desc");
			} else if ("5".equals(req.getString("sortType"))) {
				params.put("sort", "tkfee_asc");
			} else if ("6".equals(req.getString("sortType"))) {
				params.put("sort", "tkfee_desc");
			} else {
				params.put("sort", "new");
			}
			params.put("jh", "haitao");// 海淘或者极有家，值为空：全部商品，haitao：海淘商品，jiyoujia：极有家商品
			JSONObject jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_all, params);
			logger.debug("折淘客返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("status"))) {
				res.setResultNote(jsonObject.getString("content"));
				return res;
			}
			JSONArray dataList = jsonObject.getJSONArray("content");
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 首页精品专区列表
	 * @param req
	 * @return
	 */
	@PostMapping("/boutiqueList")
	@ResponseBody
	public ResJson boutiqueList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		try {
			// 商品列表
			Map<String, String> params = Maps.newHashMap();
			params.put("page", req.getPageNo() + "");// 分页获取数据,第几页
			params.put("page_size", req.getPageSize() + "");// 每页数据条数（默认每页20条），可自定义1-50之间
			params.put("sort", "new");// 按照综合排序
			params.put("sale_num_start", "10000");// 月销量≥ 值为空：全部商品，=500：月销量≥500的商品，=10000：月销量≥10000的商品
			JSONObject jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_all, params);
			logger.debug("折淘客返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("status"))) {
				res.setResultNote(jsonObject.getString("content"));
				return res;
			}
			JSONArray dataList = jsonObject.getJSONArray("content");
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 首页精品专区列表
	 * @param req
	 * @return
	 */
	@PostMapping("/boutiquePddList")
	@ResponseBody
	public ResJson boutiquePddList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		try {
			int page =0;
			int page_size=0;
			if (StringUtils.isBlank(req.getString("pageNo"))) {
				page=1;
			}else{
				page = Integer.parseInt(req.getString("pageNo"));
			}
			if (StringUtils.isBlank(req.getString("pageSize"))) {
				page_size=10;
			}else{
				page_size = Integer.parseInt(req.getString("pageSize"));
			}
			// 商品列表
			Map<String, String> params = Maps.newHashMap();
			params.put("page",String.valueOf(page));
			params.put("page_size",String.valueOf(page_size));
			params.put("activity_tags","[4,7,13]");
			params.put("with_coupon","true");
			JSONObject jsonObject = PddUtils.duoduorouterAPI(PddUtils.router, PddUtils.searchgoods, params);
			if(jsonObject.containsKey("error_response")){
				res.setResultNote("获取失败！");
				return res;
			}
			JSONArray jsonList = jsonObject.getJSONObject("goods_search_response").getJSONArray("goods_list");
			JSONArray dataList4= new JSONArray();
			for(int i=0;i<jsonList.size();i++){
				// 遍历 jsonarray 数组，把每一个对象转成 json 对象
				JSONObject insertObj = jsonList.getJSONObject(i);
				JSONObject insertObj1 = new JSONObject();
				insertObj1.put("goods_name",insertObj.getString("goods_name"));
				insertObj1.put("goods_sign",insertObj.getString("goods_sign"));
				insertObj1.put("goods_image_url",insertObj.getString("goods_image_url"));
				insertObj1.put("min_normal_price",insertObj.getString("min_normal_price"));
				insertObj1.put("min_group_price",insertObj.getString("min_group_price"));
				insertObj1.put("sales_tip",insertObj.getString("sales_tip"));
				insertObj1.put("goods_id",insertObj.getString("goods_id"));
				insertObj1.put("promotion_rate",insertObj.getString("promotion_rate"));
				insertObj1.put("unified_tags",insertObj.getString("unified_tags"));
				insertObj1.put("coupon_discount",insertObj.getString("coupon_discount"));
				if (insertObj.containsKey("predict_promotion_rate")&&insertObj.getString("predict_promotion_rate").equals("0")) {
					insertObj1.put("is_bj","true");
				}
				dataList4.add(insertObj1);
			}
			int Total=Integer.valueOf(jsonObject.getJSONObject("goods_search_response").getString("total_count"));
			int zpage=Total/page_size;
			int yushu=Total%page_size;
			if(yushu>0){
				zpage=zpage+1;
			}
			res.setTotalCount(Total);
			res.setTotalPage(zpage);
			res.setDataList(dataList4);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 品牌闪购首页
	 * @param req
	 * @return
	 */
	@PostMapping("/brandIndex")
	@ResponseBody
	public ResJson brandIndex(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		try {
			// banner图
			Access access = accessService.findUniqueByProperty("type", "3");
			if (access != null) {
				res.put("image", getRealImage(access.getImage()));
			}
			List<Map<String, Object>> dataList = Lists.newArrayList();
			// 品牌列表
			Map<String, String> params = Maps.newHashMap();
			params.put("page", req.getPageNo() + "");// 分页获取数据,第几页
			params.put("page_size", req.getPageSize() + "");// 每页数据条数（默认每页20条），可自定义1-50之间
			JSONObject jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_pinpai_name, params);
			logger.debug("折淘客返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("status"))) {
				res.setResultNote(jsonObject.getString("content"));
				return res;
			}
			JSONArray pinpaiList = jsonObject.getJSONArray("content");
			if (pinpaiList != null && pinpaiList.size() > 0) {
				for (int i = 0; i < pinpaiList.size(); i++) {
					JSONObject pinpai = pinpaiList.getJSONObject(i);
					Map<String, Object> map = Maps.newHashMap();
					map.put("pinpaiName", pinpai.get("pinpai_name"));
					map.put("shopIcon", pinpai.get("shopIcon"));
					Map<String, String> params1 = Maps.newHashMap();
					params1.put("page", "1");// 分页获取数据,第几页
					params1.put("page_size", "3");// 每页数据条数（默认每页20条），可自定义1-50之间
					params1.put("sort", "new");// 按照返佣金额从高到低排序
					params1.put("pinpai", "1");// 精选品牌，值为空：全部商品，1：精选品牌商品
					params1.put("pinpai_name", pinpai.get("pinpai_name").toString());// 品牌名称，如：南极人、苏泊尔、美的等品牌。
					JSONObject jsonObject1 = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_all, params1);
					logger.debug("折淘客返回数据：" + jsonObject1.toString());
					if (!"200".equals(jsonObject1.getString("status"))) {
						res.setResultNote(jsonObject1.getString("content"));
						return res;
					}
					JSONArray productList = jsonObject1.getJSONArray("content");
					map.put("productList", productList);
					dataList.add(map);
				}
			}
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 品牌闪购查看更多
	 * @param req
	 * @return
	 */
	@PostMapping("/brandProductList")
	@ResponseBody
	public ResJson brandProductList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		if (StringUtils.isBlank(req.getString("pinpaiName"))) {
			res.setResultNote("品牌名称不能为空！");
			return res;
		}
		try {
			Map<String, String> params = Maps.newHashMap();
			params.put("page", req.getPageNo() + "");// 分页获取数据,第几页
			params.put("page_size", req.getPageSize() + "");// 每页数据条数（默认每页20条），可自定义1-50之间
			params.put("sort", "new");// 按照返佣金额从高到低排序
			params.put("pinpai", "1");// 精选品牌，值为空：全部商品，1：精选品牌商品
			params.put("pinpai_name", req.getString("pinpaiName"));// 品牌名称，如：南极人、苏泊尔、美的等品牌。
			JSONObject jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_all, params);
			logger.debug("折淘客返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("status"))) {
				res.setResultNote(jsonObject.getString("content"));
				return res;
			}
			JSONArray dataList = jsonObject.getJSONArray("content");
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 抖券
	 * @param req
	 * @return
	 */
	@PostMapping("/getTrillData")
	@ResponseBody
	public ResJson getTrillData(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		try {
			Map<String, String> params = Maps.newHashMap();
			params.put("page", req.getPageNo() + "");// 分页获取数据,第几页
			params.put("page_size", req.getPageSize() + "");// 每页数据条数（默认每页20条），可自定义1-50之间
			params.put("sort", "new");// 按照返佣金额从高到低排序
			JSONObject jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_videos, params);
			logger.debug("折淘客返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("status"))) {
				res.setResultNote(jsonObject.getString("content"));
				return res;
			}
			JSONArray dataList = jsonObject.getJSONArray("content");
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 搜索列表
	 * @param req
	 * @return
	 */
	@PostMapping("/searchList")
	@ResponseBody
	public ResJson searchList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		if (StringUtils.isBlank(req.getString("uid"))) {
			res.setResultNote("请先登录！");
			return res;
		}
		if (StringUtils.isBlank(req.getString("yjType"))) {
			res.setResultNote("一级类型不能为空！");
			return res;
		}
		if (StringUtils.isBlank(req.getString("ejType"))) {
			res.setResultNote("二级类型不能为空！");
			return res;
		}
		if (StringUtils.isBlank(req.getString("sortType"))) {
			res.setResultNote("排序类型不能为空！");
			return res;
		}
		if (StringUtils.isBlank(req.getString("keywords"))) {
			res.setResultNote("请输入搜索内容！");
			return res;
		}
		try {
			List<Map<String, Object>> dataList = Lists.newArrayList();
			if ("0".equals(req.getString("yjType"))) {// 改为综合
				if ("0".equals(req.getString("ejType"))) {// 我惠云店
					Product product = new Product();
					product.setAuditState("1");
					product.setState("0");
					product.setIsshow("0");
					product.setIsTuijian("1");
					Page<Product> page = new Page<Product>(req.getPageNo(), req.getPageSize());

					// 排序类型:0-综合，1-销量升序，2-销量降序，3-价格升序，4-价格降序
					if ("1".equals(req.getString("sortType"))) {
						page.setOrderBy("a.sales ASC");
					} else if ("2".equals(req.getString("sortType"))) {
						page.setOrderBy("a.sales DESC");
					} else if ("3".equals(req.getString("sortType"))) {
						page.setOrderBy("a.price ASC");
					} else if ("4".equals(req.getString("sortType"))) {
						page.setOrderBy("a.price DESC");
					}
					page = productService.findPage(page, product);
					for (Product n : page.getList()) {
						Map<String, Object> map = Maps.newHashMap();
							map.put("shopId", n.getStore().getId());
							map.put("productId", n.getId());
							map.put("coverImage", getRealImage(n.getIcon()));
							map.put("productName", n.getTitle());
							map.put("price", n.getPrice());
							map.put("originalPrice", n.getOldPrice());
							map.put("couponMoney", n.getDiscount());
							map.put("integral", n.getPoint());
							map.put("salesVolume", n.getSales());
							map.put("isdl", n.getIsDl());
							map.put("ishot", n.getIsHot());
							dataList.add(map);
					}
					res.setTotalPage(page.getTotalPage());
					res.setDataList(dataList);
				} else if ("1".equals(req.getString("ejType"))) {// 淘宝
					Map<String, String> params = Maps.newHashMap();
					params.put("page", req.getPageNo() + "");// 分页获取数据,第几页
					params.put("page_size", req.getPageSize() + "");// 每页数据条数（默认每页20条），可自定义1-50之间
					/*params.put("youquan", "1");*/
					if(StringUtils.isNotBlank(req.getString("tj"))){
						params.put("tj", "tmall");// 	是否天猫商品，值为空：全部商品，tmall：天猫商品，gold_seller：金牌卖家，taobao：淘宝商品
					}
						// 排序类型:0-综合，1-销量升序，2-销量降序，3-价格升序，4-价格降序,5-铜板升序，6-铜板降序
						if ("1".equals(req.getString("sortType"))) {
							params.put("sort", "sale_num_asc");
						} else if ("2".equals(req.getString("sortType"))) {
							params.put("sort", "sale_num_desc");
						} else if ("3".equals(req.getString("sortType"))) {
							params.put("sort", "price_asc");
						} else if ("4".equals(req.getString("sortType"))) {
							params.put("sort", "price_desc");
						} else if ("5".equals(req.getString("sortType"))) {
							params.put("sort", "commission_rate_asc");
						} else if ("6".equals(req.getString("sortType"))) {
							params.put("sort", "commission_rate_desc");
						} else {
							params.put("sort", "new");
						}
						JSONObject jsonObject1 = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_all, params);
						logger.debug("折淘客返回数据：" + jsonObject1.toString());
						if (!"200".equals(jsonObject1.getString("status"))) {
							if("301".equals(jsonObject1.getString("status"))){
								res.setResult("0");
							}
							res.setResultNote(jsonObject1.getString("content"));
							return res;
						}
						JSONArray products = jsonObject1.getJSONArray("content");
						res.setDataList(products);
				} else if ("2".equals(req.getString("ejType"))) {// 京东
					Map<String, String> params = Maps.newHashMap();
					if (StringUtils.startsWithIgnoreCase(req.getString("keywords"), "https://item.m.jd.com/product/")) {
						String skuId = StringUtils.substringBetween(req.getString("keywords"), "https://item.m.jd.com/product/", ".html");
						params.put("skuIds", skuId);
					}
//					params.put("keyword", editTkl(req.getString("keywords")));
					//params.put("keyword", parsingTkl(req.getString("keywords")));
					params.put("pageIndex", req.getPageNo() + "");
					params.put("pageSize", req.getPageSize() + "");
					/*params.put("isCoupon", "1");*/
					// 排序类型:3-价格升序，4-价格降序,5-铜板升序，6-铜板降序
					if ("3".equals(req.getString("sortType"))) {
						params.put("sortName", "price");
						params.put("sort", "asc");
					} else if ("4".equals(req.getString("sortType"))) {
						params.put("sortName", "price");
						params.put("sort", "desc");
					} else if ("5".equals(req.getString("sortType"))) {
						params.put("sortName", "commission");
						params.put("sort", "asc");
					} else if ("6".equals(req.getString("sortType"))) {
						params.put("sortName", "commission");
						params.put("sort", "desc");
					}
					JSONObject jsonObject = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.getJdUnionItems, params);
					logger.debug("喵有券返回数据：" + jsonObject.toString());
					if (!"200".equals(jsonObject.getString("code"))) {
						res.setResultNote(jsonObject.getString("msg"));
						return res;
					}
					JSONArray products = jsonObject.getJSONObject("data").getJSONArray("list");
					res.setDataList(products);
				} else if ("3".equals(req.getString("ejType"))) {// 拼多多
					Map<String, String> params = Maps.newHashMap();
					params.put("page", req.getPageNo() + "");
					params.put("page_size", req.getPageSize() + "");
					params.put("with_coupon", "true");
					// 排序类型:0-综合，1-销量升序，2-销量降序，3-价格升序，4-价格降序,5-铜板升序，6-铜板降序
					if ("1".equals(req.getString("sortType"))) {
						params.put("sort_type", "5");
					} else if ("2".equals(req.getString("sortType"))) {
						params.put("sort_type", "6");
					} else if ("3".equals(req.getString("sortType"))) {
						params.put("sort_type", "3");
					} else if ("4".equals(req.getString("sortType"))) {
						params.put("sort_type", "4");
					} else if ("5".equals(req.getString("sortType"))) {
						params.put("sort_type", "13");
					} else if ("6".equals(req.getString("sortType"))) {
						params.put("sort_type", "14");
					} else {
						params.put("sort_type", "0");
					}
					JSONObject jsonObject1 = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.getpdditem, params);
					logger.debug("喵有券返回数据：" + jsonObject1.toString());
					if (!"200".equals(jsonObject1.getString("code"))) {
						res.setResultNote(jsonObject1.getString("msg"));
						return res;
					}
					JSONArray products = jsonObject1.getJSONObject("data").getJSONArray("list");
					res.setDataList(products);
				}

			} else if ("1".equals(req.getString("yjType"))) {// 铜板
				Product product = new Product();
				product.setPoint(req.getString("keywords"));
				product.setAuditState("1");
				product.setState("0");
				product.setIsshow("0");
				Page<Product> page = new Page<Product>(req.getPageNo(), req.getPageSize());

				// 排序类型:0-综合，1-销量升序，2-销量降序，3-价格升序，4-价格降序
				if ("1".equals(req.getString("sortType"))) {
					page.setOrderBy("a.sales ASC");
				} else if ("2".equals(req.getString("sortType"))) {
					page.setOrderBy("a.sales DESC");
				} else if ("3".equals(req.getString("sortType"))) {
					page.setOrderBy("a.price ASC");
				} else if ("4".equals(req.getString("sortType"))) {
					page.setOrderBy("a.price DESC");
				}
				page = productService.findPage(page, product);
				for (Product n : page.getList()) {
					Map<String, Object> map = Maps.newHashMap();
					map.put("productCode", n.getCode());
					map.put("shopId", n.getStore().getId());
					map.put("productId", n.getId());
					map.put("coverImage", getRealImage(n.getIcon()));
					map.put("productName", n.getTitle());
					map.put("price", n.getPrice());
					map.put("originalPrice", n.getOldPrice());
					map.put("couponMoney", n.getDiscount());
					map.put("integral", n.getPoint());
					map.put("salesVolume", n.getSales());
					map.put("ishot", n.getIsHot());
					dataList.add(map);
				}
				res.setTotalPage(page.getTotalPage());
				res.setDataList(dataList);
			} else {// 关键词
				if ("0".equals(req.getString("ejType"))) {// 我惠云店
					Product product = new Product();
					//product.setTitle(parsingTkl(req.getString("keywords")));
					if ((new String(req.getString("keywords"))).endsWith("元")) {
						product.setPrice(req.getString("keywords").replace("元", "").trim());
					} else if ((new String(req.getString("keywords"))).endsWith("铜板")) {
						product.setPoint(req.getString("keywords").replace("铜板", "").trim());
					} else {
						product.setTitle(this.editTkl(req.getString("keywords")));
					}
					product.setAuditState("1");
					product.setState("0");
					product.setIsshow("0");
					Page<Product> page = new Page<Product>(req.getPageNo(), req.getPageSize());

					// 排序类型:0-综合，1-销量升序，2-销量降序，3-价格升序，4-价格降序
					if ("1".equals(req.getString("sortType"))) {
						page.setOrderBy("a.sales ASC");
					} else if ("2".equals(req.getString("sortType"))) {
						page.setOrderBy("a.sales DESC");
					} else if ("3".equals(req.getString("sortType"))) {
						page.setOrderBy("a.price ASC");
					} else if ("4".equals(req.getString("sortType"))) {
						page.setOrderBy("a.price DESC");
					}
					page = productService.findPage(page, product);
					for (Product n : page.getList()) {
						Map<String, Object> map = Maps.newHashMap();
						map.put("productCode", n.getCode());
						map.put("shopId", n.getStore().getId());
						map.put("productId", n.getId());
						map.put("coverImage", getRealImage(n.getIcon()));
						map.put("productName", n.getTitle());
						map.put("price", n.getPrice());
						map.put("originalPrice", n.getOldPrice());
						map.put("couponMoney", n.getDiscount());
						map.put("integral", n.getPoint());
						map.put("salesVolume", n.getSales());
						map.put("isdl", n.getIsDl());
						map.put("ishot", n.getIsHot());
						dataList.add(map);
					}
					res.setTotalPage(page.getTotalPage());
					res.setDataList(dataList);
				} else if ("1".equals(req.getString("ejType"))) {// 淘宝
					Map<String, String> params = Maps.newHashMap();
					params.put("page", req.getPageNo() + "");// 分页获取数据,第几页
					params.put("page_size", req.getPageSize() + "");// 每页数据条数（默认每页20条），可自定义1-50之间
					/*params.put("youquan", "1");*/
					if(StringUtils.isNotBlank(req.getString("tj"))){
						params.put("tj", "tmall");
					}
					JSONObject object = parsingTkl(req.getString("keywords"));
					JSONArray dList = object.getJSONArray("dataList");
					if (dList != null) {
						res.setDataList(dList);
					} else {
						params.put("q", object.getString("content"));
						// 排序类型:0-综合，1-销量升序，2-销量降序，3-价格升序，4-价格降序,5-铜板升序，6-铜板降序
						if ("1".equals(req.getString("sortType"))) {
							params.put("sort", "sale_num_asc");
						} else if ("2".equals(req.getString("sortType"))) {
							params.put("sort", "sale_num_desc");
						} else if ("3".equals(req.getString("sortType"))) {
							params.put("sort", "price_asc");
						} else if ("4".equals(req.getString("sortType"))) {
							params.put("sort", "price_desc");
						} else if ("5".equals(req.getString("sortType"))) {
							params.put("sort", "commission_rate_asc");
						} else if ("6".equals(req.getString("sortType"))) {
							params.put("sort", "commission_rate_desc");
						} else {
							params.put("sort", "new");
						}
						JSONObject jsonObject1 = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_quanwang, params);
						logger.debug("折淘客返回数据：" + jsonObject1.toString());
						if (!"200".equals(jsonObject1.getString("status"))) {
							if("301".equals(jsonObject1.getString("status"))){
								res.setResult("0");
							}
							res.setResultNote(jsonObject1.getString("content"));
							return res;
						}
						JSONArray products = jsonObject1.getJSONArray("content");
						res.setDataList(products);
					}
				} else if ("2".equals(req.getString("ejType"))) {// 京东
					Map<String, String> params = Maps.newHashMap();
					if (StringUtils.startsWithIgnoreCase(req.getString("keywords"), "https://item.m.jd.com/product/")) {
						// https://item.m.jd.com/product/5236075.html?wxa_abtest=o&utm_user=plusmember&ad_od=share&utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=CopyURL
						String skuId = StringUtils.substringBetween(req.getString("keywords"), "https://item.m.jd.com/product/", ".html");
						params.put("skuIds", skuId);
					}
					params.put("keyword", editTkl(req.getString("keywords")));
					//params.put("keyword", parsingTkl(req.getString("keywords")));
					params.put("pageIndex", req.getPageNo() + "");
					params.put("pageSize", req.getPageSize() + "");
					/*params.put("isCoupon", "1");*/
					// 排序类型:3-价格升序，4-价格降序,5-铜板升序，6-铜板降序
					if ("3".equals(req.getString("sortType"))) {
						params.put("sortName", "price");
						params.put("sort", "asc");
					} else if ("4".equals(req.getString("sortType"))) {
						params.put("sortName", "price");
						params.put("sort", "desc");
					} else if ("5".equals(req.getString("sortType"))) {
						params.put("sortName", "commission");
						params.put("sort", "asc");
					} else if ("6".equals(req.getString("sortType"))) {
						params.put("sortName", "commission");
						params.put("sort", "desc");
					}
					JSONObject jsonObject = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.getJdUnionItems, params);
					logger.debug("喵有券返回数据：" + jsonObject.toString());
					if (!"200".equals(jsonObject.getString("code"))) {
						res.setResultNote(jsonObject.getString("msg"));
						return res;
					}
					JSONArray products = jsonObject.getJSONObject("data").getJSONArray("list");
					res.setDataList(products);
				} else if ("3".equals(req.getString("ejType"))) {// 拼多多
					//查询备案存在不存在
					Map<String, String> params10 = Maps.newHashMap();
					Map<String, String> params11 = Maps.newHashMap();

                    Member member=memberService.get(req.getString("uid"));
					if(StringUtils.isBlank(member.getPddId())){
						//调用喵有券创建推广位接口给当前用户生成一个推广位id
						Map<String, String> params12 = Maps.newHashMap();
						params12.put("pdname", MiaoyouquanUtils.pdname);
						params12.put("number", "1");
						JSONObject jsonObject = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.docreatepddpid, params12);
						logger.debug("喵有券返回数据：" + jsonObject.toString());
						if ("200".equals(jsonObject.getString("code"))) {
							JSONObject dataObject=jsonObject.getJSONObject("data");
							if(dataObject!=null){
								JSONArray pidList=dataObject.getJSONArray("p_id_list");
								if(pidList!=null && pidList.size()>0){
									member.setPddId(pidList.getJSONObject(0).getString("p_id"));
									memberService.save(member);
								}
							}
						}
					}
					params10.put("pid",member.getPddId());
					params10.put("custom_parameters", "['uid':'"+req.getString("uid")+"','sid':'111']");
					JSONObject jsonObject10 = PddUtils.duoduorouterAPI(PddUtils.router, PddUtils.getauthority, params10);
					if (jsonObject10.containsKey("error_response")) {
						res.setResult("1");
						res.setResultNote("获取失败");
						return res;
					}
					if(jsonObject10.getJSONObject("authority_query_response").getString("bind").equals("0")){
						params11.put("channel_type","10");
						params11.put("p_id_list", "['"+member.getPddId()+"']");
						params11.put("generate_we_app","true");
						params11.put("custom_parameters", "['uid':'"+req.getString("uid")+"','sid':'111']");
						JSONObject jsonObject11 = PddUtils.duoduorouterAPI(PddUtils.router, PddUtils.addbnprom, params11);
						if (jsonObject10.containsKey("error_response")) {
							res.setResult("1");
							res.setResultNote("获取失败");
							return res;
						}
						res.setResult("0");
						res.setResultNote("请去拼多多授权！");
						JSONObject url= (JSONObject) jsonObject11.getJSONObject("rp_promotion_url_generate_response").getJSONArray("url_list").get(0);
						res.put("mobile_url",url.getString("url"));
						JSONObject wxpay= (JSONObject) jsonObject11.getJSONObject("rp_promotion_url_generate_response").getJSONArray("url_list").get(0);
						res.put("we_app_info",wxpay.getJSONObject("we_app_info"));
                        JSONArray  jsonnullArray = new  JSONArray ();
                        res.setDataList(jsonnullArray);
						return res;
					}
					Map<String, String> params = Maps.newHashMap();
					String isgoods_id="";
					//goods_id_list
					// https://mobile.yangkeduo.com/goods.html?goods_id=12364804&page_from=35&share_uin=WYZMLVJVOXC3JKQTVUGNUDEDWM_GEXDA&refer_share_id=7956588e9a9e44adacdcc5d4a0f53c56&refer_share_uid=3981600428&refer_share_channel=copy_link
					String keyWord=req.getString("keywords");
					String[] splitWord = keyWord.split("\\?");
					if (StringUtils.startsWithIgnoreCase(req.getString("keywords"), "https://mobile.yangkeduo.com/")) {
						String datas = splitWord[1];
						String[] split = datas.split("&");
						for (String s : split) {
							if (StringUtils.startsWith(s, "goods_id=")) {
								params.put("goods_id_list", StringUtils.substringAfter(s, "goods_id="));
								isgoods_id = StringUtils.substringAfter(s, "goods_id=");
								break;
							}
						}
					}

					params.put("page", req.getPageNo() + "");
					params.put("page_size", req.getPageSize() + "");
					params.put("pid",member.getPddId());
					params.put("custom_parameters", "['uid':'"+req.getString("uid")+"','sid':'111']");
					params.put("with_coupon", "true");
					params.put("keyword", editTkl(req.getString("keywords")));
					//params.put("keyword", parsingTkl(req.getString("keywords")));
					// 排序类型:0-综合，1-销量升序，2-销量降序，3-价格升序，4-价格降序,5-铜板升序，6-铜板降序
					if ("1".equals(req.getString("sortType"))) {
						params.put("sort_type", "5");
					} else if ("2".equals(req.getString("sortType"))) {
						params.put("sort_type", "6");
					} else if ("3".equals(req.getString("sortType"))) {
						params.put("sort_type", "3");
					} else if ("4".equals(req.getString("sortType"))) {
						params.put("sort_type", "4");
					} else if ("5".equals(req.getString("sortType"))) {
						params.put("sort_type", "13");
					} else if ("6".equals(req.getString("sortType"))) {
						params.put("sort_type", "14");
					} else {
						params.put("sort_type", "0");
					}
					if(!isBlank(isgoods_id) && isgoods_id != "null"){
						//根据goods_id获取goods_sign
						Map<String, String> params5 = Maps.newHashMap();
						System.out.println("________________________________________________________________________");
						params5.put("with_coupon","true");
						params5.put("keyword", isgoods_id);
						params5.put("pid",member.getPddId());
						params5.put("custom_parameters", "['uid':'"+req.getString("uid")+"','sid':'111']");
						JSONObject jsonObject5 = PddUtils.duoduorouterAPI(PddUtils.router, PddUtils.searchgoods, params5);
						logger.debug("拼多多返回数据：" + jsonObject5.toString());
						if(!StringUtils.isBlank(jsonObject5.getString("error_response"))){
							res.setResult("1");
							res.setResultNote("该商品未获取/或不存在");
							return res;
						}
//						JSONObject dataObject5=jsonObject5.getJSONObject("goods_search_response");
						JSONArray dataList5 = jsonObject5.getJSONObject("goods_search_response").getJSONArray("goods_list");//获取详情
						JSONObject obj = dataList5.getJSONObject(0);
						JSONArray dataList3=new  JSONArray ();
						for(int i=0;i<dataList5.size();i++){
							// 遍历 jsonarray 数组，把每一个对象转成 json 对象
							JSONObject insertObj = dataList5.getJSONObject(i);
							insertObj.put("goods_gallery_urls", "");
							insertObj.put("opt_ids", "");
							insertObj.put("cat_ids", "");
							insertObj.put("is_bj","false");
							if (insertObj.containsKey("predict_promotion_rate")&&insertObj.getString("predict_promotion_rate").equals("0")) {
								insertObj.put("is_bj","true");
							}
							dataList3.add(insertObj);
						}
						res.setDataList(dataList3);
					}else{
						JSONObject jsonObject1 = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.getpdditem, params);
						logger.debug("喵有券返回数据：" + jsonObject1.toString());
						if (!"200".equals(jsonObject1.getString("code"))) {
							res.setResultNote(jsonObject1.getString("msg"));
							return res;
						}
						JSONArray products = jsonObject1.getJSONObject("data").getJSONArray("list");
						JSONArray products_list= new  JSONArray ();
						for(int i=0;i<products.size();i++){
							// 遍历 jsonarray 数组，把每一个对象转成 json 对象
							JSONObject insertObj1 = products.getJSONObject(i);
								insertObj1.put("is_bj","false");
							if (insertObj1.containsKey("predict_promotion_rate")&&insertObj1.getString("predict_promotion_rate").equals("0")) {
								insertObj1.put("is_bj","true");
							}
							products_list.add(insertObj1);
						}
						res.setDataList(products_list);
					}
				}
			}
			res.setResult("0");
            res.put("mobile_url","");//拼多多授权链接
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	private String editTkl(String content) {
		return content.replaceAll(" +", "").length() > 30
					? content.replaceAll(" +", "").substring(0, 30) : content.replaceAll(" +", "");
	}

	/**
	 * 拼多多
	 * @param req
	 * @return
	 */
	@PostMapping("/pinduoduoIndex")
	@ResponseBody
	public ResJson pinduoduoIndex(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		if (StringUtils.isBlank(req.getString("sortType"))) {
			res.setResultNote("排序类型不能为空！");
			return res;
		}
		try {
			//轮播图
			List<Map<String, Object>> bannerList = Lists.newArrayList();
			Banner banner = new Banner();
			banner.setType("10");
			List<Banner> list = bannerService.findList(banner);
			for (Banner b : list) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("image", getRealImage(b.getImage()));
				map.put("category", b.getCategory());
				map.put("url", b.getUrl());
				map.put("productId", b.getProduct() != null ? b.getProduct().getId() : "");
				map.put("storeId", b.getStore() != null ? b.getStore().getId() : "");
				map.put("thirdLink", StringUtils.isNotBlank(b.getThirdLink()) ? b.getThirdLink() : "");
				map.put("productCategoryId", b.getProductCategory() != null ? b.getProductCategory().getId() : "");
				map.put("productCategoryName", b.getProductCategory() != null ? b.getProductCategory().getName() : "");
				bannerList.add(map);
			}
			res.put("bannerList", bannerList);

			// 一级分类列表
			List<Map<String, Object>> categoryList = Lists.newArrayList();
			/*Map<String, String> params = Maps.newHashMap();
			params.put("parent_opt_id", "0");
			JSONObject jsonObject = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.getpddopts, params);
			logger.debug("喵有券返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("code"))) {
				res.setResultNote(jsonObject.getString("msg"));
				return res;
			}
			JSONArray dataArray = jsonObject.getJSONArray("data");
			if (dataArray != null) {
				for (int i = 0; i < dataArray.size(); i++) {
					JSONObject c = dataArray.getJSONObject(i);
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("id", c.get("opt_id"));
					map.put("name", c.get("opt_name"));
					categoryList.add(map);
				}
			}
			res.put("categoryList", removeRepeatMapByKey(categoryList, "name"));*/
			PddCategory pddCategory = new PddCategory();
			pddCategory.setState("0");
			List<PddCategory> pddcategoryList = pddCategoryService.findList(pddCategory);
			for (PddCategory cagegory : pddcategoryList) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", cagegory.getId());
				map.put("name", cagegory.getName());
				map.put("icon", getRealImage(cagegory.getIcon()));
				categoryList.add(map);
			}
			res.put("categoryList", categoryList);

			Map<String, String> params1 = Maps.newHashMap();
			params1.put("page", req.getPageNo()+"");
			params1.put("page_size", req.getPageSize() + "");
			params1.put("with_coupon", "true");
//			params1.put("opt_id", "14");
			// 排序类型:0-综合，1-销量升序，2-销量降序，3-价格升序，4-价格降序,5-铜板升序，6-铜板降序
			if ("1".equals(req.getString("sortType"))) {
				params1.put("sort_type", "5");
			} else if ("2".equals(req.getString("sortType"))) {
				params1.put("sort_type", "6");
			} else if ("3".equals(req.getString("sortType"))) {
				params1.put("sort_type", "3");
			} else if ("4".equals(req.getString("sortType"))) {
				params1.put("sort_type", "4");
			} else if ("5".equals(req.getString("sortType"))) {
				params1.put("sort_type", "13");
			} else if ("6".equals(req.getString("sortType"))) {
				params1.put("sort_type", "14");
			} else {
				params1.put("sort_type", "0");
			}
			JSONObject jsonObject1 = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.getpdditem, params1);
			logger.debug("喵有券返回数据：" + jsonObject1.toString());
			if (!"200".equals(jsonObject1.getString("code"))) {
				res.setResultNote(jsonObject1.getString("msg"));
				return res;
			}
			JSONArray dataList = jsonObject1.getJSONObject("data").getJSONArray("list");
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 拼多多根据分类ID查询商品列表
	 * @param req
	 * @return
	 */
	@PostMapping("/pinduoduoProductList")
	@ResponseBody
	public ResJson pinduoduoProductList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		if (StringUtils.isBlank(req.getString("categoryId"))) {
			res.setResultNote("分类ID不能为空！");
			return res;
		}
		if (StringUtils.isBlank(req.getString("sortType"))) {
			res.setResultNote("排序类型不能为空！");
			return res;
		}
		try {
			Map<String, String> params1 = Maps.newHashMap();
			params1.put("page", req.getPageNo() + "");
			params1.put("page_size", req.getPageSize() + "");
			params1.put("with_coupon", "true");
			params1.put("opt_id", req.getString("categoryId"));
			// 排序类型:0-综合，1-销量升序，2-销量降序，3-价格升序，4-价格降序,5-铜板升序，6-铜板降序
			if ("1".equals(req.getString("sortType"))) {
				params1.put("sort_type", "5");
			} else if ("2".equals(req.getString("sortType"))) {
				params1.put("sort_type", "6");
			} else if ("3".equals(req.getString("sortType"))) {
				params1.put("sort_type", "3");
			} else if ("4".equals(req.getString("sortType"))) {
				params1.put("sort_type", "4");
			} else if ("5".equals(req.getString("sortType"))) {
				params1.put("sort_type", "13");
			} else if ("6".equals(req.getString("sortType"))) {
				params1.put("sort_type", "14");
			} else {
				params1.put("sort_type", "0");
			}
			JSONObject jsonObject1 = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.getpdditem, params1);
			logger.debug("喵有券返回数据：" + jsonObject1.toString());
			if (!"200".equals(jsonObject1.getString("code"))) {
				res.setResultNote(jsonObject1.getString("msg"));
				return res;
			}
			JSONArray dataList = jsonObject1.getJSONObject("data").getJSONArray("list");
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 获取拼多多商品推广链接API
	 * @param req
	 * @return
	 */
	@PostMapping("/getpdditemtgurl")
	@ResponseBody
	public ResJson getpdditemtgurl(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		if (StringUtils.isBlank(req.getString("productId"))) {
			res.setResultNote("商品ID不能为空！");
			return res;
		}
		if (StringUtils.isBlank(req.getString("uid"))) {
			res.setResultNote("用户ID不能为空！");
			return res;
		}
		if (!req.containsKey("type")) {
			req.put("type","0");//微信小程序
		}else{
			req.put("type","1");
		}
		try {
			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}
			if(StringUtils.isBlank(member.getPddId())){
				//调用喵有券创建推广位接口给当前用户生成一个推广位id
				Map<String, String> params = Maps.newHashMap();
				params.put("pdname", MiaoyouquanUtils.pdname);
				params.put("number", "1");
				JSONObject jsonObject = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.docreatepddpid, params);
				logger.debug("喵有券返回数据：" + jsonObject.toString());
				if ("200".equals(jsonObject.getString("code"))) {
					JSONObject dataObject=jsonObject.getJSONObject("data");
					if(dataObject!=null){
						JSONArray pidList=dataObject.getJSONArray("p_id_list");
						if(pidList!=null && pidList.size()>0){
							member.setPddId(pidList.getJSONObject(0).getString("p_id"));
							memberService.save(member);
						}
					}
				}
			}
			Map<String, String> params10 = Maps.newHashMap();
			params10.put("pid",member.getPddId());
			params10.put("custom_parameters", "['uid':'"+req.getString("uid")+"','sid':'111']");
			JSONObject jsonObject10 = PddUtils.duoduorouterAPI(PddUtils.router, PddUtils.getauthority, params10);
			if (jsonObject10.containsKey("error_response")) {
				res.setResult("1");
				res.setResultNote("获取失败");
				return res;
			}
			if(jsonObject10.getJSONObject("authority_query_response").getString("bind").equals("0")){
				Map<String, String> params11 = Maps.newHashMap();
				params11.put("channel_type","10");
				params11.put("generate_we_app","true");
				params11.put("p_id_list", "['"+member.getPddId()+"']");
				params11.put("custom_parameters", "['uid':'"+req.getString("uid")+"','sid':'111']");
				JSONObject jsonObject11 = PddUtils.duoduorouterAPI(PddUtils.router, PddUtils.addbnprom, params11);
				res.setResult("0");
				res.setResultNote("请去拼多多授权！");
				JSONObject url= (JSONObject) jsonObject11.getJSONObject("rp_promotion_url_generate_response").getJSONArray("url_list").get(0);
				res.put("mobile_url",url.getString("url"));
				JSONObject wxpay= (JSONObject) jsonObject11.getJSONObject("rp_promotion_url_generate_response").getJSONArray("url_list").get(0);
				res.put("we_app_info",wxpay.getJSONObject("we_app_info"));
				return res;
			}
			Map<String, String> params = Maps.newHashMap();
			params.put("p_id", member.getPddId());
			params.put("custom_parameters", "['uid':'"+req.getString("uid")+"','sid':'111']");
			params.put("pdname", MiaoyouquanUtils.pdname);
			params.put("goods_sign", req.getString("productId"));
			if(req.getString("type").equals("1")){
				params.put("generate_we_app", "true");
			}
			params.put("generate_short_url", "true");
			params.put("generate_weapp_webview", "true");
			JSONObject jsonObject = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.getpdditemtgurl, params);
			logger.debug("喵有券返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("code"))) {
				res.setResultNote(jsonObject.getString("msg"));
				return res;
			}
			JSONArray dataList = jsonObject.getJSONObject("data").getJSONArray("url");
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 拼多多商品详情
	 * @param req
	 * @return
	 */
	@PostMapping("/pinduoduoProductDetail")
	@ResponseBody
	public ResJson pinduoduoProductDetail(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.put("mobile_url","");
		res.setResultNote("查询失败");
		if (StringUtils.isBlank(req.getString("goods_id"))) {
			res.setResultNote("商品ID不能为空！");
			return res;
		}
		if (StringUtils.isBlank(req.getString("uid"))) {
			res.setResultNote("请先登录！");
			return res;
		}
		//查询备案存在不存在
		Map<String, String> params10 = Maps.newHashMap();
		Map<String, String> params11 = Maps.newHashMap();
		Member member=memberService.get(req.getString("uid"));
		if(StringUtils.isBlank(member.getPddId())){
			//调用喵有券创建推广位接口给当前用户生成一个推广位id
			Map<String, String> params12 = Maps.newHashMap();
			params12.put("pdname", MiaoyouquanUtils.pdname);
			params12.put("number", "1");
			JSONObject jsonObject = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.docreatepddpid, params12);
			logger.debug("喵有券返回数据：" + jsonObject.toString());
			if ("200".equals(jsonObject.getString("code"))) {
				JSONObject dataObject=jsonObject.getJSONObject("data");
				if(dataObject!=null){
					JSONArray pidList=dataObject.getJSONArray("p_id_list");
					if(pidList!=null && pidList.size()>0){
						member.setPddId(pidList.getJSONObject(0).getString("p_id"));
						memberService.save(member);
					}
				}
			}
		}
		params10.put("pid",member.getPddId());
		params10.put("custom_parameters", "['uid':'"+req.getString("uid")+"','sid':'111']");
		JSONObject jsonObject10 = PddUtils.duoduorouterAPI(PddUtils.router, PddUtils.getauthority, params10);
		if (jsonObject10.containsKey("error_response")) {
			res.setResult("1");
			res.setResultNote("获取失败");
			return res;
		}
		if(jsonObject10.getJSONObject("authority_query_response").getString("bind").equals("0")){
			params11.put("channel_type","10");
			params11.put("generate_we_app","true");
			params11.put("p_id_list", "['"+member.getPddId()+"']");
			params11.put("custom_parameters", "['uid':'"+req.getString("uid")+"','sid':'111']");
			JSONObject jsonObject11 = PddUtils.duoduorouterAPI(PddUtils.router, PddUtils.addbnprom, params11);
			if (jsonObject10.containsKey("error_response")) {
				res.setResult("1");
				res.setResultNote("获取失败");
				return res;
			}
			res.setResult("0");
			res.setResultNote("请去拼多多授权！");
			JSONObject url= (JSONObject) jsonObject11.getJSONObject("rp_promotion_url_generate_response").getJSONArray("url_list").get(0);
			res.put("mobile_url",url.getString("url"));
			JSONObject wxpay= (JSONObject) jsonObject11.getJSONObject("rp_promotion_url_generate_response").getJSONArray("url_list").get(0);
			res.put("we_app_info",wxpay.getJSONObject("we_app_info"));
		}

		try {
			Map<String, String> params = Maps.newHashMap();
			params.put("pid",member.getPddId());
			params.put("custom_parameters", "['uid':'"+req.getString("uid")+"','sid':'111']");
			params.put("goods_sign", req.getString("goods_id"));
			JSONObject jsonObject = PddUtils.duoduorouterAPI(PddUtils.router,PddUtils.getGoodsDetailInfo, params);
			logger.debug("拼多多返回数据：" + jsonObject.toString());
			if (jsonObject.containsKey("error_response")) {
				String sub_msg= jsonObject.getJSONObject("error_response").getString("error_msg");
				if(sub_msg!= null){
					res.setResultNote(sub_msg);
					return res;
				}
				res.setResultNote("数据返回异常！");
				return res;
			}
			JSONArray dataList = jsonObject.getJSONObject("goods_detail_response").getJSONArray("goods_details");
			JSONArray dataList4= new JSONArray();
			for(int i=0;i<dataList.size();i++){
				// 遍历 jsonarray 数组，把每一个对象转成 json 对象
				JSONObject insertObj = dataList.getJSONObject(i);
				insertObj.put("goods_gallery_urls", "");
				insertObj.put("opt_ids", "");
				insertObj.put("cat_ids", "");
				insertObj.put("is_bj","false");
				if (insertObj.containsKey("predict_promotion_rate")&&insertObj.getString("predict_promotion_rate").equals("0")) {
					insertObj.put("is_bj","true");
				}
				dataList4.add(insertObj);
			}
			res.setDataList(dataList4);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}


	/**
	 * 京东
	 * @param req
	 * @return
	 */
	@PostMapping("/jingdongIndex")
	@ResponseBody
	public ResJson jingdongIndex(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		try {
			// 轮播图
			List<Map<String, Object>> bannerList = Lists.newArrayList();
			Banner banner = new Banner();
			banner.setType("8");
			List<Banner> list = bannerService.findList(banner);
			for (Banner b : list) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("image", getRealImage(b.getImage()));
				map.put("category", b.getCategory());
				map.put("url", b.getUrl());
				map.put("productId", b.getProduct() != null ? b.getProduct().getId() : "");
				map.put("storeId", b.getStore() != null ? b.getStore().getId() : "");
				map.put("thirdLink", StringUtils.isNotBlank(b.getThirdLink()) ? b.getThirdLink() : "");
				map.put("productCategoryId", b.getProductCategory() != null ? b.getProductCategory().getId() : "");
				map.put("productCategoryName", b.getProductCategory() != null ? b.getProductCategory().getName() : "");
				bannerList.add(map);
			}
			res.put("bannerList", bannerList);

			// 一级分类列表
			List<Map<String, Object>> categoryList = Lists.newArrayList();
			/*Map<String, String> params = Maps.newHashMap();
			params.put("parent_id", "0");
			params.put("grade", "0");
			JSONObject jsonObject = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.getItemCateInfo, params);
			logger.debug("喵有券返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("code"))) {
				res.setResultNote(jsonObject.getString("msg"));
				return res;
			}
			JSONArray dataArray = jsonObject.getJSONArray("data");
			if (dataArray != null) {
				for (int i = 0; i < dataArray.size(); i++) {
					JSONObject c = dataArray.getJSONObject(i);
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("id", c.get("id"));
					map.put("name", c.get("name"));
					categoryList.add(map);
				}
			}*/
			JdCategory jdCategory = new JdCategory();
			jdCategory.setState("0");
			List<JdCategory> jdcategoryList = jdCategoryService.findList(jdCategory);
			for (JdCategory cagegory : jdcategoryList) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", cagegory.getId());
				map.put("name", cagegory.getName());
				map.put("icon", getRealImage(cagegory.getIcon()));
				categoryList.add(map);
			}
			res.put("categoryList", categoryList);

			Map<String, String> params = Maps.newHashMap();
			params.put("pageIndex", req.getPageNo() + "");
			params.put("pageSize", req.getPageSize() + "");
			params.put("cid1", "1316");
			/*params.put("eliteId", "1");*/
			// 排序类型:3-价格升序，4-价格降序,5-铜板升序，6-铜板降序
			if ("3".equals(req.getString("sortType"))) {
				params.put("sortName", "price");
				params.put("sort", "asc");
			} else if ("4".equals(req.getString("sortType"))) {
				params.put("sortName", "price");
				params.put("sort", "desc");
			} else if ("5".equals(req.getString("sortType"))) {
				params.put("sortName", "commission");
				params.put("sort", "asc");
			} else if ("6".equals(req.getString("sortType"))) {
				params.put("sortName", "commission");
				params.put("sort", "desc");
			}
			JSONObject jsonObject = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.getJdUnionItems, params);
			logger.debug("喵有券返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("code"))) {
				res.setResultNote(jsonObject.getString("msg"));
				return res;
			}
			JSONArray dataList = jsonObject.getJSONObject("data").getJSONArray("list");
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 京东根据分类ID查询商品列表
	 * @param req
	 * @return
	 */
	@PostMapping("/jingdongProductList")
	@ResponseBody
	public ResJson jingdongProductList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		if (StringUtils.isBlank(req.getString("categoryId"))) {
			res.setResultNote("分类ID不能为空！");
			return res;
		}
		try {
			Map<String, String> params = Maps.newHashMap();
			params.put("cid1", req.getString("categoryId"));
			params.put("pageIndex", req.getPageNo() + "");
			params.put("pageSize", req.getPageSize() + "");
			/*params.put("isCoupon", "1");*/
			// 排序类型:3-价格升序，4-价格降序,5-铜板升序，6-铜板降序
			if ("3".equals(req.getString("sortType"))) {
				params.put("sortName", "price");
				params.put("sort", "asc");
			} else if ("4".equals(req.getString("sortType"))) {
				params.put("sortName", "price");
				params.put("sort", "desc");
			} else if ("5".equals(req.getString("sortType"))) {
				params.put("sortName", "commission");
				params.put("sort", "asc");
			} else if ("6".equals(req.getString("sortType"))) {
				params.put("sortName", "commission");
				params.put("sort", "desc");
			}
			JSONObject jsonObject = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.getJdUnionItems, params);
			logger.debug("喵有券返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("code"))) {
				res.setResultNote(jsonObject.getString("msg"));
				return res;
			}
			JSONArray dataList = jsonObject.getJSONObject("data").getJSONArray("list");
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 京东商品详情
	 * @param req
	 * @return
	 */
	@PostMapping("/jdProductDetail")
	@ResponseBody
	public ResJson jingdongProductDetail(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		if (StringUtils.isBlank(req.getString("skuid"))) {
			res.setResultNote("商品ID不能为空！");
			return res;
		}
		try {
			Map<String, String> params = Maps.newHashMap();
			params.put("skuid", req.getString("skuid"));
			JSONObject jsonObject = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.getItemInfo, params);
			logger.debug("喵有券返回数据：" + jsonObject.toString());
			JSONArray dataList = jsonObject.getJSONObject("data").getJSONArray("ItemInfo");
			res.setDataList(dataList);
			JSONArray descPic = jsonObject.getJSONObject("data").getJSONArray("descPic");
			if(descPic == null){
				JSONArray  data2 = new JSONArray();
				descPic =data2;
			}
			res.put("descPic", descPic);
			JSONObject itemCouponInfo = jsonObject.getJSONObject("data").getJSONObject("itemCouponInfo");
			res.put("itemCouponInfo", itemCouponInfo);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 获取商品推广链接(支持subUnionId)
	 * @param req
	 * @return
	 */
	@PostMapping("/doItemCpsUrl")
	@ResponseBody
	public ResJson doItemCpsUrl(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		if (StringUtils.isBlank(req.getString("materialId"))) {
			res.setResultNote("商品详情页不能为空！");
			return res;
		}
		if (StringUtils.isBlank(req.getString("uid"))) {
			res.setResultNote("用户ID不能为空！");
			return res;
		}
	/*	if (StringUtils.isBlank(req.getString("couponUrl"))) {
			res.setResultNote("优惠券链接不能为空！");
			return res;
		}*/
		try {
			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}
			if (StringUtils.isBlank(member.getJdId())) {
				String spaceNameList = IdGen.getOrderNo();// 推广位名称
				// 调用喵有券创建推广位接口给当前用户生成一个推广位id
				Map<String, String> params = Maps.newHashMap();
				params.put("key_id", MiaoyouquanUtils.lmdykey);
				params.put("unionType", "1");
				params.put("type", "2");
				params.put("spaceNameList", spaceNameList);
				params.put("siteId", MiaoyouquanUtils.siteId);
				JSONObject jsonObject = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.createUnionPosition, params);
				logger.debug("喵有券返回数据：" + jsonObject.toString());
				if (!"200".equals(jsonObject.getString("code"))) {
					res.setResultNote(jsonObject.getString("msg"));
					return res;
				}
				JSONObject dataObject = jsonObject.getJSONObject("data");
				if (dataObject != null) {
					JSONObject resultList = dataObject.getJSONObject("resultList");
					if (resultList != null) {
						member.setJdId(resultList.getString(spaceNameList));
						memberService.save(member);
					}
				}
			}
			Map<String, String> params = Maps.newHashMap();
			params.put("materialId", URLEncoder.encode(req.getString("materialId"), "UTF-8"));
			params.put("key_id", MiaoyouquanUtils.lmdykey);
			params.put("positionId", member.getJdId());
			if (StringUtils.isNotBlank(req.getString("couponUrl"))) {
				params.put("couponUrl", URLEncoder.encode(req.getString("couponUrl"), "UTF-8"));
			}
			JSONObject jsonObject = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.doItemCpsUrl, params);
			logger.debug("喵有券返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("code"))) {
				res.setResultNote(jsonObject.getString("msg"));
				return res;
			}
			JSONObject data = jsonObject.getJSONObject("data");
			res.put("data", data);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 天猫
	 * @param req
	 * @return
	 */
	@PostMapping("/tmallIndex")
	@ResponseBody
	public ResJson tmallIndex(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		if (StringUtils.isBlank(req.getString("sortType"))) {
			res.setResultNote("排序类型不能为空！");
			return res;
		}
		try {
			// 轮播图
			List<Map<String, Object>> bannerList = Lists.newArrayList();
			Banner banner = new Banner();
			banner.setType("6");
			List<Banner> list = bannerService.findList(banner);
			for (Banner b : list) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("image", getRealImage(b.getImage()));
				map.put("category", b.getCategory());
				map.put("url", b.getUrl());
				map.put("productId", b.getProduct() != null ? b.getProduct().getId() : "");
				map.put("storeId", b.getStore() != null ? b.getStore().getId() : "");
				map.put("thirdLink", StringUtils.isNotBlank(b.getThirdLink()) ? b.getThirdLink() : "");
				map.put("productCategoryId", b.getProductCategory() != null ? b.getProductCategory().getId() : "");
				map.put("productCategoryName", b.getProductCategory() != null ? b.getProductCategory().getName() : "");
				bannerList.add(map);
			}
			res.put("bannerList", bannerList);
			// 一级分类列表
			List<Map<String, Object>> categoryList = Lists.newArrayList();
			JSONObject jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_type, Maps.newHashMap());
			logger.debug("折淘客返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("status"))) {
				res.setResultNote(jsonObject.getString("content"));
				return res;
			}
			JSONArray dataArray = jsonObject.getJSONArray("type");
			if (dataArray != null) {
				for (int i = 0; i < dataArray.size(); i++) {
					JSONObject c = dataArray.getJSONObject(i);
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("id", c.get("cid"));
					map.put("name", c.get("name"));
					map.put("icon", c.get("q_pic"));
					categoryList.add(map);
				}
			}
			res.put("categoryList", removeRepeatMapByKey(categoryList, "id"));
			Map<String, String> params = Maps.newHashMap();
			params.put("page", req.getPageNo() + "");// 分页获取数据,第几页
			params.put("page_size", req.getPageSize() + "");// 每页数据条数（默认每页20条），可自定义1-50之间
			params.put("tj", "tmall");
			// 排序类型:0-综合，1-销量升序，2-销量降序，3-价格升序，4-价格降序,5-铜板升序，6-铜板降序
			if ("1".equals(req.getString("sortType"))) {
				params.put("sort", "sale_num_asc");
			} else if ("2".equals(req.getString("sortType"))) {
				params.put("sort", "sale_num_desc");
			} else if ("3".equals(req.getString("sortType"))) {
				params.put("sort", "price_asc");
			} else if ("4".equals(req.getString("sortType"))) {
				params.put("sort", "price_desc");
			} else if ("5".equals(req.getString("sortType"))) {
				params.put("sort", "tkfee_asc");
			} else if ("6".equals(req.getString("sortType"))) {
				params.put("sort", "tkfee_desc");
			} else {
				params.put("sort", "new");
			}
			JSONObject jsonObject1 = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_all, params);
			logger.debug("折淘客返回数据：" + jsonObject1.toString());
			if (!"200".equals(jsonObject1.getString("status"))) {
				if("301".equals(jsonObject1.getString("status"))){
					res.setResult("0");
				}
				res.setResultNote(jsonObject1.getString("content"));
				return res;
			}
			JSONArray dataList = jsonObject1.getJSONArray("content");
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 天猫根据分类ID查询商品列表
	 * @param req
	 * @return
	 */
	@PostMapping("/tmallProductList")
	@ResponseBody
	public ResJson tmallProductList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		if (StringUtils.isBlank(req.getString("sortType"))) {
			res.setResultNote("排序类型不能为空！");
			return res;
		}
		if (StringUtils.isBlank(req.getString("categoryId"))) {
			res.setResultNote("分类ID不能为空！");
			return res;
		}
		try {
			Map<String, String> params = Maps.newHashMap();
			params.put("page", req.getPageNo() + "");// 分页获取数据,第几页
			params.put("page_size", req.getPageSize() + "");// 每页数据条数（默认每页20条），可自定义1-50之间
			params.put("cid", req.getString("categoryId"));
			// 排序类型:0-综合，1-销量升序，2-销量降序，3-价格升序，4-价格降序,5-铜板升序，6-铜板降序
			if ("1".equals(req.getString("sortType"))) {
				params.put("sort", "sale_num_asc");
			} else if ("2".equals(req.getString("sortType"))) {
				params.put("sort", "sale_num_desc");
			} else if ("3".equals(req.getString("sortType"))) {
				params.put("sort", "price_asc");
			} else if ("4".equals(req.getString("sortType"))) {
				params.put("sort", "price_desc");
			} else if ("5".equals(req.getString("sortType"))) {
				params.put("sort", "tkfee_asc");
			} else if ("6".equals(req.getString("sortType"))) {
				params.put("sort", "tkfee_desc");
			} else {
				params.put("sort", "new");
			}
			JSONObject jsonObject1 = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_all, params);
			logger.debug("折淘客返回数据：" + jsonObject1.toString());
			if (!"200".equals(jsonObject1.getString("status"))) {
				if("301".equals(jsonObject1.getString("status"))){
					res.setResult("0");
				}
				res.setResultNote(jsonObject1.getString("content"));
				return res;
			}
			JSONArray dataList = jsonObject1.getJSONArray("content");
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 我惠云超
	 * @param req
	 * @return
	 */
	@PostMapping("/yunChao")
	@ResponseBody
	public ResJson yunChao(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		try {
			// 轮播图
			List<Map<String, Object>> bannerList = Lists.newArrayList();
			Banner banner = new Banner();
			banner.setType("5");
			List<Banner> list = bannerService.findList(banner);
			for (Banner b : list) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("image", getRealImage(b.getImage()));
				map.put("category", b.getCategory());
				map.put("url", b.getUrl());
				map.put("productId", b.getProduct() != null ? b.getProduct().getId() : "");
				map.put("storeId", b.getStore() != null ? b.getStore().getId() : "");
				map.put("thirdLink", StringUtils.isNotBlank(b.getThirdLink()) ? b.getThirdLink() : "");
				map.put("productCategoryId", b.getProductCategory() != null ? b.getProductCategory().getId() : "");
				map.put("productCategoryName", b.getProductCategory() != null ? b.getProductCategory().getName() : "");
				bannerList.add(map);
			}
			res.put("bannerList", bannerList);
			// 一级分类列表
			List<Map<String, Object>> categoryList = Lists.newArrayList();
			JSONObject jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_type, Maps.newHashMap());
			logger.debug("折淘客返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("status"))) {
				res.setResultNote(jsonObject.getString("content"));
				return res;
			}
			JSONArray dataArray = jsonObject.getJSONArray("type");
			if (dataArray != null) {
				for (int i = 0; i < dataArray.size(); i++) {
					JSONObject c = dataArray.getJSONObject(i);
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("id", c.get("cid"));
					map.put("name", c.get("name"));
					map.put("icon", c.get("q_pic"));
					categoryList.add(map);
				}
			}
			res.put("categoryList", removeRepeatMapByKey(categoryList, "id"));
			Map<String, String> params = Maps.newHashMap();
			params.put("page", req.getPageNo() + "");// 分页获取数据,第几页
			params.put("page_size", req.getPageSize() + "");// 每页数据条数（默认每页20条），可自定义1-50之间
			//params.put("sort", "new");
			// 排序类型:0-综合，1-销量升序，2-销量降序，3-价格升序，4-价格降序,5-铜板升序，6-铜板降序
			if ("1".equals(req.getString("sortType"))) {
				params.put("sort", "sale_num_asc");
			} else if ("2".equals(req.getString("sortType"))) {
				params.put("sort", "sale_num_desc");
			} else if ("3".equals(req.getString("sortType"))) {
				params.put("sort", "price_asc");
			} else if ("4".equals(req.getString("sortType"))) {
				params.put("sort", "price_desc");
			} else if ("5".equals(req.getString("sortType"))) {
				params.put("sort", "tkfee_asc");
			} else if ("6".equals(req.getString("sortType"))) {
				params.put("sort", "tkfee_desc");
			} else {
				params.put("sort", "new");
			}
			params.put("tianmaochaoshi", "1");
			JSONObject jsonObject1 = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_all, params);
			logger.debug("折淘客返回数据：" + jsonObject1.toString());
			if (!"200".equals(jsonObject1.getString("status"))) {
				if("301".equals(jsonObject1.getString("status"))){
					res.setResult("0");
				}
				res.setResultNote(jsonObject1.getString("content"));
				return res;
			}
			JSONArray dataList = jsonObject1.getJSONArray("content");
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 我惠云超根据分类ID查询商品列表
	 * @param req
	 * @return
	 */
	@PostMapping("/findYunChaoListByCategoryId")
	@ResponseBody
	public ResJson findYunChaoListByCategoryId(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		if (StringUtils.isBlank(req.getString("sortType"))) {
			res.setResultNote("排序类型不能为空！");
			return res;
		}
		if (StringUtils.isBlank(req.getString("categoryId"))) {
			res.setResultNote("分类ID不能为空！");
			return res;
		}
		try {
			Map<String, String> params = Maps.newHashMap();
			params.put("page", req.getPageNo() + "");// 分页获取数据,第几页
			params.put("page_size", req.getPageSize() + "");// 每页数据条数（默认每页20条），可自定义1-50之间
			params.put("cid", req.getString("categoryId"));
			params.put("tianmaochaoshi", "1");
			// 排序类型:0-综合，1-销量升序，2-销量降序，3-价格升序，4-价格降序,5-铜板升序，6-铜板降序
			if ("1".equals(req.getString("sortType"))) {
				params.put("sort", "sale_num_asc");
			} else if ("2".equals(req.getString("sortType"))) {
				params.put("sort", "sale_num_desc");
			} else if ("3".equals(req.getString("sortType"))) {
				params.put("sort", "price_asc");
			} else if ("4".equals(req.getString("sortType"))) {
				params.put("sort", "price_desc");
			} else if ("5".equals(req.getString("sortType"))) {
				params.put("sort", "tkfee_asc");
			} else if ("6".equals(req.getString("sortType"))) {
				params.put("sort", "tkfee_desc");
			} else {
				params.put("sort", "new");
			}
			JSONObject jsonObject1 = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_all, params);
			logger.debug("折淘客返回数据：" + jsonObject1.toString());
			if (!"200".equals(jsonObject1.getString("status"))) {
				if("301".equals(jsonObject1.getString("status"))){
					res.setResult("0");
				}
				res.setResultNote(jsonObject1.getString("content"));
				return res;
			}
			JSONArray dataList = jsonObject1.getJSONArray("content");
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 聚划算
	 * @param req
	 * @return
	 */
	@PostMapping("/juhuasuanIndex")
	@ResponseBody
	public ResJson juhuasuanIndex(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		if (StringUtils.isBlank(req.getString("sortType"))) {
			res.setResultNote("排序类型不能为空！");
			return res;
		}
		try {
			// 轮播图
			List<Map<String, Object>> bannerList = Lists.newArrayList();
			Banner banner = new Banner();
			banner.setType("9");
			List<Banner> list = bannerService.findList(banner);
			for (Banner b : list) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("image", getRealImage(b.getImage()));
				map.put("category", b.getCategory());
				map.put("url", b.getUrl());
				map.put("productId", b.getProduct() != null ? b.getProduct().getId() : "");
				map.put("storeId", b.getStore() != null ? b.getStore().getId() : "");
				map.put("thirdLink", StringUtils.isNotBlank(b.getThirdLink()) ? b.getThirdLink() : "");
				map.put("productCategoryId", b.getProductCategory() != null ? b.getProductCategory().getId() : "");
				map.put("productCategoryName", b.getProductCategory() != null ? b.getProductCategory().getName() : "");
				bannerList.add(map);
			}
			res.put("bannerList", bannerList);
			// 一级分类列表
			List<Map<String, Object>> categoryList = Lists.newArrayList();
			JSONObject jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_type, Maps.newHashMap());
			logger.debug("折淘客返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("status"))) {
				res.setResultNote(jsonObject.getString("content"));
				return res;
			}
			JSONArray dataArray = jsonObject.getJSONArray("type");
			if (dataArray != null) {
				for (int i = 0; i < dataArray.size(); i++) {
					JSONObject c = dataArray.getJSONObject(i);
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("id", c.get("cid"));
					map.put("name", c.get("name"));
					map.put("icon", c.get("q_pic"));
					categoryList.add(map);
				}
			}
			res.put("categoryList", removeRepeatMapByKey(categoryList, "id"));
			Map<String, String> params = Maps.newHashMap();
			params.put("page", req.getPageNo() + "");// 分页获取数据,第几页
			params.put("page_size", req.getPageSize() + "");// 每页数据条数（默认每页20条），可自定义1-50之间
			params.put("jt", "juhuasuan");
			// 排序类型:0-综合，1-销量升序，2-销量降序，3-价格升序，4-价格降序,5-铜板升序，6-铜板降序
			if ("1".equals(req.getString("sortType"))) {
				params.put("sort", "sale_num_asc");
			} else if ("2".equals(req.getString("sortType"))) {
				params.put("sort", "sale_num_desc");
			} else if ("3".equals(req.getString("sortType"))) {
				params.put("sort", "price_asc");
			} else if ("4".equals(req.getString("sortType"))) {
				params.put("sort", "price_desc");
			} else if ("5".equals(req.getString("sortType"))) {
				params.put("sort", "tkfee_asc");
			} else if ("6".equals(req.getString("sortType"))) {
				params.put("sort", "tkfee_desc");
			} else {
				params.put("sort", "new");
			}
			JSONObject jsonObject1 = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_all, params);
			logger.debug("折淘客返回数据：" + jsonObject1.toString());
			if (!"200".equals(jsonObject1.getString("status"))) {
				if("301".equals(jsonObject1.getString("status"))){
					res.setResult("0");
				}
				res.setResultNote(jsonObject1.getString("content"));
				return res;
			}
			JSONArray dataList = jsonObject1.getJSONArray("content");
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 聚划算根据分类ID查询商品列表
	 * @param req
	 * @return
	 */
	@PostMapping("/juhuasuanProductList")
	@ResponseBody
	public ResJson juhuasuanProductList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		if (StringUtils.isBlank(req.getString("sortType"))) {
			res.setResultNote("排序类型不能为空！");
			return res;
		}
		if (StringUtils.isBlank(req.getString("categoryId"))) {
			res.setResultNote("分类ID不能为空！");
			return res;
		}
		try {
			Map<String, String> params = Maps.newHashMap();
			params.put("page", req.getPageNo() + "");// 分页获取数据,第几页
			params.put("page_size", req.getPageSize() + "");// 每页数据条数（默认每页20条），可自定义1-50之间
			params.put("cid", req.getString("categoryId"));
			params.put("jt", "juhuasuan");
			// 排序类型:0-综合，1-销量升序，2-销量降序，3-价格升序，4-价格降序,5-铜板升序，6-铜板降序
			if ("1".equals(req.getString("sortType"))) {
				params.put("sort", "sale_num_asc");
			} else if ("2".equals(req.getString("sortType"))) {
				params.put("sort", "sale_num_desc");
			} else if ("3".equals(req.getString("sortType"))) {
				params.put("sort", "price_asc");
			} else if ("4".equals(req.getString("sortType"))) {
				params.put("sort", "price_desc");
			} else if ("5".equals(req.getString("sortType"))) {
				params.put("sort", "tkfee_asc");
			} else if ("6".equals(req.getString("sortType"))) {
				params.put("sort", "tkfee_desc");
			} else {
				params.put("sort", "new");
			}
			JSONObject jsonObject1 = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_all, params);
			logger.debug("折淘客返回数据：" + jsonObject1.toString());
			if (!"200".equals(jsonObject1.getString("status"))) {
				if("301".equals(jsonObject1.getString("status"))){
					res.setResult("0");
				}
				res.setResultNote(jsonObject1.getString("content"));
				return res;
			}
			JSONArray dataList = jsonObject1.getJSONArray("content");
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 折淘客商品详情（包含云超，天猫，聚划算）
	 * @param req
	 * @return
	 */
	@PostMapping("/zetaokeDetail")
	@ResponseBody
	public ResJson zetaokeDetail(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		if (StringUtils.isBlank(req.getString("tao_id"))) {
			res.setResultNote("商品ID不能为空！");
			return res;
		}
		try {
			//商品详情
			Map<String, String> params = Maps.newHashMap();
			params.put("tao_id", req.getString("tao_id"));// 单个商品ID
			JSONObject jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_detail, params);
			logger.debug("折淘客返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("status"))) {
				res.setResultNote(jsonObject.getString("content"));
				return res;
			}
			res.put("detail", jsonObject);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 猜你喜欢（天猫，云超，聚划算）
	 * @param req
	 * @return
	 */
	@PostMapping("/zetaokeLike")
	@ResponseBody
	public ResJson zetaokeLike(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		if (StringUtils.isBlank(req.getString("productId"))) {
			res.setResultNote("商品ID不能为空！");
			return res;
		}
		try {
			Map<String, String> params = Maps.newHashMap();
			params.put("page", req.getPageNo() + "");// 分页获取数据,第几页
			params.put("page_size", req.getPageSize() + "");// 每页数据条数（默认每页20条），可自定义1-50之间
			params.put("item_id", req.getString("productId"));
			JSONObject jsonObject1 = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.open_item_guess_like, params);
			logger.debug("折淘客返回数据：" + jsonObject1.toString());
			if (!"200".equals(jsonObject1.getString("status"))) {
				res.setResultNote(jsonObject1.getString("content"));
				return res;
			}
			JSONArray dataList = jsonObject1.getJSONArray("content");
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 折淘客高佣转链API接口
	 * @param req
	 * @return
	 */
	@PostMapping("/gaoyongzhuanlian")
	@ResponseBody
	public ResJson gaoyongzhuanlian(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		if (StringUtils.isBlank(req.getString("uid"))) {
			res.setResultNote("用户ID不能为空！");
			return res;
		}
		if (StringUtils.isBlank(req.getString("tao_id"))) {
			res.setResultNote("商品ID不能为空！");
			return res;
		}
		try {
			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}
			if(StringUtils.isNotBlank(member.getRelationId())){
				Map<String, String> params = Maps.newHashMap();
				params.put("sid", MiaoyouquanUtils.sid);// 对应的淘客账号授权ID
				params.put("pid", MiaoyouquanUtils.pid);// 淘客PID，mm_xxx_xxx_xxx,三段格式，必须与授权的账户相同，否则出错
				params.put("num_iid", req.getString("tao_id"));// 商品ID,商品ID或me必须填一个
				params.put("relation_id", member.getRelationId());// 渠道关系ID，仅适用于渠道推广场景。
				params.put("signurl", "1");// 值为1或者2，表示返回淘宝联盟请求地址，大家拿到地址后再用自己的服务器二次请求即可获得最终结果，值为1返回http链接，值为2返回https安全链接。
				JSONObject jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.open_gaoyongzhuanlian, params);
				logger.debug("折淘客返回数据：" + jsonObject.toString());
				if ("301".equals(jsonObject.getString("status"))) {
					res.setResultNote(jsonObject.getString("content"));
					return res;
				}
				JSONObject urlObject=JSONObject.parseObject(HttpClientUtil.doGet(jsonObject.getString("url")));
				if(urlObject!=null){
					res.put("coupon_click_url", urlObject.getJSONObject("tbk_privilege_get_response").getJSONObject("result").getJSONObject("data").getString("coupon_click_url"));
				}
				res.put("isGet", "1");
			}else{
				res.put("isGet", "0");
			}
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}


	/**
	 * 绑定淘宝
	 * @param req
	 * @return
	 */
	@PostMapping("/bindTaobao")
	@ResponseBody
	public ResJson bindTaobao(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("绑定失败");
		if (StringUtils.isBlank(req.getString("uid"))) {
			res.setResultNote("用户ID不能为空！");
			return res;
		}
		if (StringUtils.isBlank(req.getString("relation_id"))) {
			res.setResultNote("渠道ID不能为空！");
			return res;
		}
		try {
			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}
			//判断渠道ID有没有被绑定过
			Member member1 = memberService.findUniqueByProperty("relation_id", req.getString("relation_id"));
			if(member1!=null){
				res.setResultNote("该淘宝已被绑定过！");
				return res;
			}
			member.setRelationId(req.getString("relation_id"));
			memberService.save(member);
			res.setResult("0");
			res.setResultNote("绑定成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 淘客订单列表
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/AmoyOrderList")
	@ResponseBody
	public ResJson AmoyOrderList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		List<Map<String, Object>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("userType"))) {
				res.setResultNote("用户类型不能为空！");
				return res;
			}
			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}
			TTaokeOrder taokeOrder = new TTaokeOrder();
			if ("0".equals(req.getString("userType"))) {// 本人订单
				taokeOrder.setMember(member);
			} else {// 客户订单
				taokeOrder.setDataScope(
						" AND a.uid IN(SELECT id FROM t_member WHERE invite_id='" + req.getString("uid") + "') ");
			}
			if ("0".equals(req.getString("type"))) {// 已付款
				taokeOrder.setTkStatus("12,0,1,16");
			} else if ("1".equals(req.getString("type"))) {// 已结算
				taokeOrder.setTkStatus("3,5,18");
			} else if ("2".equals(req.getString("type"))) {// 已失效
				taokeOrder.setTkStatus("13,20");
			}
			Page<TTaokeOrder> page = tTaokeOrderService
					.findPage(new Page<TTaokeOrder>(req.getPageNo(), req.getPageSize()), taokeOrder);
			for (TTaokeOrder n : page.getList()) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("type", n.getType());
				map.put("orderId", n.getId());
				map.put("orderNum", n.getTradeParentId());
				map.put("status", n.getTkStatus());
				map.put("payMoney", n.getAlipayTotalPrice());
				map.put("estimateIncome", n.getTotalCommissionFee());
				map.put("adtime", n.getTkCreateTime() != null ? DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(n.getTkCreateTime()) : "");
				map.put("productImage", n.getItemImg());
				map.put("productName", n.getItemTitle());
				map.put("price", n.getItemPrice());
				map.put("num", n.getItemNum());
				map.put("payTime", n.getTbPaidTime() != null ? DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(n.getTbPaidTime()) : "");
				map.put("productId", n.getItemId());
				map.put("goodssign", n.getGoodsSign());
				map.put("pubSharePreFee", n.getPubSharePreFee());
				if("0".equals(n.getType())){
					if("3".equals(n.getTkStatus())){
						map.put("isJs", "1");
					}else{
						map.put("isJs", "0");
					}
				}else if("1".equals(n.getType())){
					if("5".equals(n.getTkStatus())){
						map.put("isJs", "1");
					}else{
						map.put("isJs", "0");
					}
				}else if("2".equals(n.getType())){
					if("18".equals(n.getTkStatus())){
						map.put("isJs", "1");
					}else{
						map.put("isJs", "0");
					}
				}
				dataList.add(map);
			}
			res.setTotalPage(page.getTotalPage());
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}


	/**
	 * 授权登录后，拿到的accesstoken
	 * @param req
	 * @return
	 */
	@RequestMapping("/getRelationId")
	@ResponseBody
	public ResJson getRelationId(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("绑定失败");
		if (StringUtils.isBlank(req.getString("code"))) {
			res.setResultNote("CODE不能为空！");
			return res;
		}
		if (StringUtils.isBlank(req.getString("uid"))) {
			res.setResultNote("用户ID不能为空！");
			return res;
		}
		try {
			try {
				// 获取到code
				logger.debug("code:" + req.getString("code"));
				logger.debug("uid:" + req.getString("uid"));
				// 用code来换取accessToken
				String tokenUrl = "https://oauth.taobao.com/token";
				Map<String, String> props = new HashMap<String, String>();
				props.put("grant_type", "authorization_code");
				props.put("code", req.getString("code"));
				props.put("client_id", Global.getConfig("client_id"));
				props.put("client_secret", Global.getConfig("client_secret"));
				props.put("redirect_uri", Global.getConfig("redirect_uri"));
				props.put("state", "1212");
				props.put("view", "wap");
				String result = WebUtils.doPost(tokenUrl, props, 30000, 30000);
				logger.debug("result:" + result);
				String accessToken = JSONObject.parseObject(result).getString("access_token");
				logger.debug("accessToken:" + accessToken);
				// 获取到accessToken之后来获取渠道ID
				TaobaoClient client = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest",
						Global.getConfig("client_id"), Global.getConfig("client_secret"));
				TbkScPublisherInfoSaveRequest param = new TbkScPublisherInfoSaveRequest();
				param.setRelationFrom("1");
				param.setOfflineScene("4");
				param.setOnlineScene("3");
				param.setInviterCode(Global.getConfig("inviter_code"));
				param.setInfoType(1L);
				// req.setNote("小蜜蜂");
				TbkScPublisherInfoSaveResponse rsp = client.execute(param, accessToken);
				logger.debug("body:" + rsp.getBody());
				JSONObject successBody = JSON.parseObject(
						JSONObject.parseObject(rsp.getBody()).getString("tbk_sc_publisher_info_save_response"));
				logger.debug("tbk_sc_publisher_info_save_response:" + successBody);
				JSONObject errorBody = JSON
						.parseObject(JSONObject.parseObject(rsp.getBody()).getString("error_response"));
				logger.debug("error_response:" + errorBody);
				if (StringUtils.isNotBlank(JSONObject.parseObject(rsp.getBody()).getString("error_response"))) {
					res.setResultNote(errorBody.getString("sub_msg"));
					return res;
				} else {
					// 跟app用户绑定
					String relationId = JSON.parseObject(successBody.getString("data")).getString("relation_id");
					logger.debug("relationId:" + relationId);
					Member member = memberService.get(req.getString("uid"));
					if (member != null) {
						// 判断渠道ID有没有被绑定过
						Member member1 = memberService.findUniqueByProperty("relation_id", relationId);
						if (member1 == null) {
							member.setRelationId(relationId);
							memberService.save(member);
							res.put("relationId", relationId);
							res.setResult("0");
							//res.setResultNote(JSON.parseObject(successBody.getString("data")).getString("desc"));
							res.setResultNote("恭喜您，绑定成功");
						} else {
							res.put("wohui_phone",member1.getPhone());
							res.setResultNote("重复绑定");
						}
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 淘口令生成API
	 * @param req
	 * @return
	 */
	@PostMapping("/openTklCreate")
	@ResponseBody
	public ResJson openTklCreate(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		try {
			if (StringUtils.isBlank(req.getString("text"))) {
				res.setResultNote("口令弹框内容不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("url"))) {
				res.setResultNote("口令跳转目标页不能为空！");
				return res;
			}

			Map<String, String> params = Maps.newHashMap();
			params.put("sid", MiaoyouquanUtils.sid);// 对应的淘客账号授权ID
			params.put("text", URLEncoder.encode(req.getString("text"), "UTF-8"));// 口令弹框内容，长度大于5个字符
			params.put("url", URLEncoder.encode(req.getString("url"), "UTF-8"));// 口令跳转目标页
			params.put("signurl", "0");// 口令跳转目标页
			JSONObject jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.open_tkl_create, params);
			logger.debug("折淘客返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("status"))) {
				res.setResultNote(jsonObject.getString("content"));
				return res;
			}
			String model = jsonObject.getString("model");
			res.put("tkl", model);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 解除绑定应用
	 * @return
	 */
	@PostMapping({"/Removebind"})
	@ResponseBody
	public ResJson Removebind(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("解绑失败");
		if (StringUtils.isBlank(req.getString("uid"))) {
			res.setResultNote("用户ID不能为空！");
			return res;
		} else if (StringUtils.isBlank(req.getString("type"))) {
			res.setResultNote("解绑类型不能为空！");
			return res;
		} else {
			try {
				Member member = this.memberService.get(req.getString("uid"));
				if (member == null) {
					res.setResultNote("该用户不存在！");
					return res;
				}

				if ("1".equals(req.getString("type"))) {
					String tokenUrl = "https://oauth.taobao.com/logoff";
					Map<String, String> props = new HashMap();
					props.put("client_id",Global.getConfig("client_id"));
					props.put("view", "wap");
					String result = WebUtils.doGet(tokenUrl, props);
					System.out.println(result);
					member.setRelationId((String)null);
				} else if ("2".equals(req.getString("type"))) {
					member.setPddId((String)null);
				} else if ("3".equals(req.getString("type"))) {
					member.setJdId((String)null);
				}

				this.memberService.save(member);
				res.setResult("0");
				res.setResultNote("解绑成功");
			} catch (Exception var4) {
				this.logger.error(var4.getMessage());
			}

			return res;
		}
	}

	/**
	 * 匹配字符串中的淘口令(解析淘口令)
//	 * @param array
//	 * @param image
	 * @return
	 */
	private JSONObject parsingTkl(String content) {
		JSONObject obj = new JSONObject();
		String pattern = "([\\p{Sc}])\\w{8,12}([\\p{Sc}])";
		Pattern r = Pattern.compile(pattern);
		Matcher m = r.matcher(content);
		if (m.find()) {
			System.out.println("match: " + m.group());
			try {
				Map<String, String> params = Maps.newHashMap();
				params.put("sid", MiaoyouquanUtils.sid);// 对应的淘客账号授权ID
				params.put("content", URLEncoder.encode(m.group(), "UTF-8"));// 淘口令文案。请注意，该参数需要进行Urlencode编码后传入。
				params.put("type", "1");// 是否返回优惠券详细信息，type=1表示返回商品ID和优惠券详细信息，注意，优惠券信息可能为空
				JSONObject jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.open_shangpin_id, params);
				logger.debug("折淘客返回数据1：" + jsonObject.toString());
				if (StringUtils.isNotBlank(jsonObject.getString("item_id"))) {
					// 商品详情
					params = Maps.newHashMap();
					params.put("tao_id", jsonObject.getString("item_id"));// 单个商品ID
					jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_detail, params);
					logger.debug("折淘客返回数据2：" + jsonObject.toString());
					if ("200".equals(jsonObject.getString("status"))) {
						//content = jsonObject.getJSONArray("content").getJSONObject(0).getString("tao_title");
						JSONArray jsonArray = jsonObject.getJSONArray("content");
						if (jsonArray != null) {
							obj.put("dataList", jsonArray);
							return obj;
						}
					} else {
						content = content.replaceAll(" +", "").length() > 30
								? content.replaceAll(" +", "").substring(0, 30) : content.replaceAll(" +", "");
					}
				} else {
					content = content.replaceAll(" +", "").length() > 30 ? content.replaceAll(" +", "").substring(0, 30)
							: content.replaceAll(" +", "");
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		} else {
			content = content.replaceAll(" +", "").length() > 30 ? content.replaceAll(" +", "").substring(0, 30)
					: content.replaceAll(" +", "");
		}
		obj.put("content", content);
		return obj;
	}

	/**
	 * 根据map中的某个key 去除List中重复的map
	 * @param list
	 * @param mapKey
	 * @return
	 */
	public static List<Map<String, Object>> removeRepeatMapByKey(List<Map<String, Object>> list, String mapKey) {
		if (CollectionUtils.isEmpty(list))
			return null;
		// 把list中的数据转换成msp,去掉同一id值多余数据，保留查找到第一个id值对应的数据
		List<Map<String, Object>> listMap = new ArrayList<>();
		Map<String, Map> msp = new HashMap<>();
		for (int i = list.size() - 1; i >= 0; i--) {
			Map map = list.get(i);
			String id = (String) map.get(mapKey);
			map.remove(mapKey);
			msp.put(id, map);
		}
		// 把msp再转换成list,就会得到根据某一字段去掉重复的数据的List<Map>
		Set<String> mspKey = msp.keySet();
		for (String key : mspKey) {
			Map newMap = msp.get(key);
			newMap.put(mapKey, key);
			listMap.add(newMap);
		}
		return listMap;
	}

	/**
	 * 检测是否为空
	 * @param values
	 * @return
	 */
	private boolean isBlank(String...values) {
		for (String value : values) {
			if (StringUtils.isBlank(value)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 获取图片真实路径
	 * @param image
	 * @return
	 */
	private String getRealImage(String image) {
		if (StringUtils.isNotBlank(image)) {
			if (image.startsWith("http")) {
				return image;
			}
			return filePath + image;
		}
		return "";
	}

	/**
	 * 根据手机号获取缓存中的验证码
	 * @param phone
	 * @return
	 */
	private String getCaptcha(String phone) {
		return (String) CacheProviderHolder.getLevel2Cache(UserUtils.CAPTCHA_CACHE).get(phone);
	}

	/**
	 * 清除缓存中指定手机号的验证码
	 * @param phone
	 */
	private void removeCaptcha(String phone) {
		CacheProviderHolder.getLevel2Cache(UserUtils.CAPTCHA_CACHE).evict(phone);
	}

	private ResJson test(ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {

		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
}
